diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7fdc67e..0000000 --- a/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: java -jdk: - - oraclejdk8 -env: - - DIR=all_code/UnitParser - - DIR=all_code/Test -script: cd $DIR && ant build -notifications: - email: false \ No newline at end of file diff --git a/all_comments/UnitParser.doc.zip b/UnitParser.doc.zip similarity index 100% rename from all_comments/UnitParser.doc.zip rename to UnitParser.doc.zip diff --git a/all_binaries/NumberParser.jar b/all_binaries/NumberParser.jar deleted file mode 100644 index ee95ed8..0000000 Binary files a/all_binaries/NumberParser.jar and /dev/null differ diff --git a/all_binaries/NumberParser_without_javadoc.jar b/all_binaries/NumberParser_without_javadoc.jar deleted file mode 100644 index 47ed954..0000000 Binary files a/all_binaries/NumberParser_without_javadoc.jar and /dev/null differ diff --git a/all_code/.metadata/.bak_0.log b/all_code/.metadata/.bak_0.log deleted file mode 100644 index 7204c77..0000000 --- a/all_code/.metadata/.bak_0.log +++ /dev/null @@ -1,18869 +0,0 @@ -!SESSION 2017-05-27 19:54:17.091 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -This is a continuation of log file C:\Users\Alvaro\Desktop\workspace\.metadata\.bak_3.log -Created Time: 2017-05-27 20:05:29.218 - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:29.218 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:29.219 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:33.748 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:33.749 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:33.750 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:36.198 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:36.198 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:36.199 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:36.218 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:36.219 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:36.219 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:39.209 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:39.210 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:39.211 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:39.863 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:39.864 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:39.865 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:41.893 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:41.894 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:41.894 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:43.728 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:43.729 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:43.729 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:43.753 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:43.753 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:43.754 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:44.760 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:44.761 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:44.762 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:44.900 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:44.901 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:44.901 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:45.794 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:45.795 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:45.795 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:45.814 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:45.815 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:45.815 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:47.897 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:47.897 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:47.897 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:47.988 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:47.989 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:47.989 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:48.628 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:48.629 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:48.630 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:50.826 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - temp = new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:50.827 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:50.828 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:51.191 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - temp = new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:51.192 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:51.192 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:52.864 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - temp = new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:52.865 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:52.866 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:52.888 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - temp = new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:52.889 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:52.889 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:57.708 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - else - { - temp = new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:57.709 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:57.710 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) -!SESSION 2017-05-29 13:41:51.196 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.core.resources 4 567 2017-05-29 13:41:52.845 -!MESSAGE Workspace restored, but some problems occurred. -!SUBENTRY 1 org.eclipse.core.resources 4 567 2017-05-29 13:41:52.846 -!MESSAGE Could not read metadata for 'UnitParser'. -!STACK 1 -org.eclipse.core.internal.resources.ResourceException: The project description file (.project) for 'UnitParser' is missing. This file contains important information about the project. The project will not function properly until this file is restored. - at org.eclipse.core.internal.localstore.FileSystemResourceManager.read(FileSystemResourceManager.java:907) - at org.eclipse.core.internal.resources.SaveManager.restoreMetaInfo(SaveManager.java:904) - at org.eclipse.core.internal.resources.SaveManager.restoreMetaInfo(SaveManager.java:884) - at org.eclipse.core.internal.resources.SaveManager.restore(SaveManager.java:735) - at org.eclipse.core.internal.resources.SaveManager.startup(SaveManager.java:1587) - at org.eclipse.core.internal.resources.Workspace.startup(Workspace.java:2399) - at org.eclipse.core.internal.resources.Workspace.open(Workspace.java:2156) - at org.eclipse.core.resources.ResourcesPlugin.start(ResourcesPlugin.java:464) - at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:774) - at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1) - at java.security.AccessController.doPrivileged(Native Method) - at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:767) - at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:724) - at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:932) - at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:309) - at org.eclipse.osgi.container.Module.doStart(Module.java:581) - at org.eclipse.osgi.container.Module.start(Module.java:449) - at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:470) - at org.eclipse.osgi.internal.hooks.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:107) - at org.eclipse.osgi.internal.loader.classpath.ClasspathManager.findLocalClass(ClasspathManager.java:529) - at org.eclipse.osgi.internal.loader.ModuleClassLoader.findLocalClass(ModuleClassLoader.java:325) - at org.eclipse.osgi.internal.loader.BundleLoader.findLocalClass(BundleLoader.java:345) - at org.eclipse.osgi.internal.loader.sources.SingleSourcePackage.loadClass(SingleSourcePackage.java:36) - at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:419) - at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:372) - at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:364) - at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:161) - at java.lang.ClassLoader.loadClass(Unknown Source) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 2 org.eclipse.core.resources 4 567 2017-05-29 13:41:52.847 -!MESSAGE The project description file (.project) for 'UnitParser' is missing. This file contains important information about the project. The project will not function properly until this file is restored. -!SUBENTRY 1 org.eclipse.core.resources 4 567 2017-05-29 13:41:52.847 -!MESSAGE Could not read metadata for 'testing'. -!STACK 1 -org.eclipse.core.internal.resources.ResourceException: The project description file (.project) for 'testing' is missing. This file contains important information about the project. The project will not function properly until this file is restored. - at org.eclipse.core.internal.localstore.FileSystemResourceManager.read(FileSystemResourceManager.java:907) - at org.eclipse.core.internal.resources.SaveManager.restoreMetaInfo(SaveManager.java:904) - at org.eclipse.core.internal.resources.SaveManager.restoreMetaInfo(SaveManager.java:884) - at org.eclipse.core.internal.resources.SaveManager.restore(SaveManager.java:735) - at org.eclipse.core.internal.resources.SaveManager.startup(SaveManager.java:1587) - at org.eclipse.core.internal.resources.Workspace.startup(Workspace.java:2399) - at org.eclipse.core.internal.resources.Workspace.open(Workspace.java:2156) - at org.eclipse.core.resources.ResourcesPlugin.start(ResourcesPlugin.java:464) - at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:774) - at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1) - at java.security.AccessController.doPrivileged(Native Method) - at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:767) - at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:724) - at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:932) - at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:309) - at org.eclipse.osgi.container.Module.doStart(Module.java:581) - at org.eclipse.osgi.container.Module.start(Module.java:449) - at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:470) - at org.eclipse.osgi.internal.hooks.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:107) - at org.eclipse.osgi.internal.loader.classpath.ClasspathManager.findLocalClass(ClasspathManager.java:529) - at org.eclipse.osgi.internal.loader.ModuleClassLoader.findLocalClass(ModuleClassLoader.java:325) - at org.eclipse.osgi.internal.loader.BundleLoader.findLocalClass(BundleLoader.java:345) - at org.eclipse.osgi.internal.loader.sources.SingleSourcePackage.loadClass(SingleSourcePackage.java:36) - at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:419) - at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:372) - at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:364) - at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:161) - at java.lang.ClassLoader.loadClass(Unknown Source) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 2 org.eclipse.core.resources 4 567 2017-05-29 13:41:52.848 -!MESSAGE The project description file (.project) for 'testing' is missing. This file contains important information about the project. The project will not function properly until this file is restored. - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-29 13:41:58.536 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-05-29 13:42:10.211 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-29 13:42:16.493 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.recommenders.rcp 4 18 2017-05-29 14:02:46.918 -!MESSAGE Failed to resolve selection in ‘=testing/src Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.recommenders.subwords.rcp 4 1 2017-05-29 16:00:48.718 -!MESSAGE Exception during code completion -!STACK 0 -org.eclipse.core.runtime.OperationCanceledException - at org.eclipse.jdt.internal.codeassist.CompletionEngine.checkCancel(CompletionEngine.java:1688) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.completionOnSingleNameReference(CompletionEngine.java:3298) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:1718) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:1944) - at org.eclipse.jdt.internal.core.Openable.codeComplete(Openable.java:131) - at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:357) - at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:345) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.computeProposals(SubwordsSessionProcessor.java:338) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.getNewProposals(SubwordsSessionProcessor.java:227) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.initializeContext(SubwordsSessionProcessor.java:167) - at org.eclipse.recommenders.completion.rcp.processable.IntelligentCompletionProposalComputer.fireInitializeContext(IntelligentCompletionProposalComputer.java:292) - at org.eclipse.recommenders.completion.rcp.processable.IntelligentCompletionProposalComputer.computeCompletionProposals(IntelligentCompletionProposalComputer.java:169) - at org.eclipse.jdt.internal.ui.text.java.CompletionProposalComputerDescriptor.computeCompletionProposals(CompletionProposalComputerDescriptor.java:333) - at org.eclipse.jdt.internal.ui.text.java.CompletionProposalCategory.computeCompletionProposals(CompletionProposalCategory.java:337) - at org.eclipse.jdt.internal.ui.text.java.ContentAssistProcessor.collectProposals(ContentAssistProcessor.java:331) - at org.eclipse.jdt.internal.ui.text.java.ContentAssistProcessor.computeCompletionProposals(ContentAssistProcessor.java:288) - at org.eclipse.jface.text.contentassist.ContentAssistant$3.run(ContentAssistant.java:1931) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals(ContentAssistant.java:1928) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals(CompletionProposalPopup.java:565) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeFilteredProposals(CompletionProposalPopup.java:1523) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$4(CompletionProposalPopup.java:1512) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:362) - at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) - at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182) - at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4211) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3827) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 2 0 2017-05-29 16:00:48.747 -!MESSAGE The 'org.eclipse.recommenders.completion.rcp.javaCompletionProposalComputer.intelligent' proposal computer from the 'org.eclipse.recommenders.completion.rcp' plug-in did not complete normally. The extension took too long to return from the 'computeCompletionProposals()' operation. - -!ENTRY org.eclipse.recommenders.subwords.rcp 4 1 2017-05-29 16:02:33.420 -!MESSAGE Exception during code completion -!STACK 0 -org.eclipse.core.runtime.OperationCanceledException - at org.eclipse.jdt.internal.codeassist.CompletionEngine.checkCancel(CompletionEngine.java:1688) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.completionOnSingleNameReference(CompletionEngine.java:3298) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:1718) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:1944) - at org.eclipse.jdt.internal.core.Openable.codeComplete(Openable.java:131) - at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:357) - at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:345) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.computeProposals(SubwordsSessionProcessor.java:338) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.getNewProposals(SubwordsSessionProcessor.java:227) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.initializeContext(SubwordsSessionProcessor.java:167) - at org.eclipse.recommenders.completion.rcp.processable.IntelligentCompletionProposalComputer.fireInitializeContext(IntelligentCompletionProposalComputer.java:292) - at org.eclipse.recommenders.completion.rcp.processable.IntelligentCompletionProposalComputer.computeCompletionProposals(IntelligentCompletionProposalComputer.java:169) - at org.eclipse.jdt.internal.ui.text.java.CompletionProposalComputerDescriptor.computeCompletionProposals(CompletionProposalComputerDescriptor.java:333) - at org.eclipse.jdt.internal.ui.text.java.CompletionProposalCategory.computeCompletionProposals(CompletionProposalCategory.java:337) - at org.eclipse.jdt.internal.ui.text.java.ContentAssistProcessor.collectProposals(ContentAssistProcessor.java:331) - at org.eclipse.jdt.internal.ui.text.java.ContentAssistProcessor.computeCompletionProposals(ContentAssistProcessor.java:288) - at org.eclipse.jface.text.contentassist.ContentAssistant$3.run(ContentAssistant.java:1931) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals(ContentAssistant.java:1928) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals(CompletionProposalPopup.java:565) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeFilteredProposals(CompletionProposalPopup.java:1523) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$4(CompletionProposalPopup.java:1512) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:362) - at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) - at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182) - at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4211) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3827) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 2 0 2017-05-29 16:02:33.433 -!MESSAGE The 'org.eclipse.recommenders.completion.rcp.javaCompletionProposalComputer.intelligent' proposal computer from the 'org.eclipse.recommenders.completion.rcp' plug-in did not complete normally. The extension took too long to return from the 'computeCompletionProposals()' operation. - -!ENTRY org.eclipse.recommenders.subwords.rcp 4 1 2017-05-29 16:08:57.339 -!MESSAGE Exception during code completion -!STACK 0 -org.eclipse.core.runtime.OperationCanceledException - at org.eclipse.jdt.internal.codeassist.CompletionEngine.checkCancel(CompletionEngine.java:1688) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.completionOnSingleNameReference(CompletionEngine.java:3298) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:1718) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:1944) - at org.eclipse.jdt.internal.core.Openable.codeComplete(Openable.java:131) - at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:357) - at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:345) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.computeProposals(SubwordsSessionProcessor.java:338) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.getNewProposals(SubwordsSessionProcessor.java:227) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.initializeContext(SubwordsSessionProcessor.java:167) - at org.eclipse.recommenders.completion.rcp.processable.IntelligentCompletionProposalComputer.fireInitializeContext(IntelligentCompletionProposalComputer.java:292) - at org.eclipse.recommenders.completion.rcp.processable.IntelligentCompletionProposalComputer.computeCompletionProposals(IntelligentCompletionProposalComputer.java:169) - at org.eclipse.jdt.internal.ui.text.java.CompletionProposalComputerDescriptor.computeCompletionProposals(CompletionProposalComputerDescriptor.java:333) - at org.eclipse.jdt.internal.ui.text.java.CompletionProposalCategory.computeCompletionProposals(CompletionProposalCategory.java:337) - at org.eclipse.jdt.internal.ui.text.java.ContentAssistProcessor.collectProposals(ContentAssistProcessor.java:331) - at org.eclipse.jdt.internal.ui.text.java.ContentAssistProcessor.computeCompletionProposals(ContentAssistProcessor.java:288) - at org.eclipse.jface.text.contentassist.ContentAssistant$3.run(ContentAssistant.java:1931) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals(ContentAssistant.java:1928) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals(CompletionProposalPopup.java:565) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeFilteredProposals(CompletionProposalPopup.java:1523) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$4(CompletionProposalPopup.java:1512) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:362) - at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) - at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182) - at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4211) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3827) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 2 0 2017-05-29 16:08:57.344 -!MESSAGE The 'org.eclipse.recommenders.completion.rcp.javaCompletionProposalComputer.intelligent' proposal computer from the 'org.eclipse.recommenders.completion.rcp' plug-in did not complete normally. The extension took too long to return from the 'computeCompletionProposals()' operation. - -!ENTRY org.eclipse.jdt.ui 4 10001 2017-05-29 16:19:21.800 -!MESSAGE Internal Error -!STACK 1 -Java Model Exception: Core Exception [code 0] Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -Caused by: org.eclipse.core.runtime.CoreException: Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 1 org.eclipse.jdt.ui 4 0 2017-05-29 16:19:21.800 -!MESSAGE Illegal hierarchy - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-29 17:04:40.924 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.ClassCastException: org.eclipse.jdt.internal.core.TypeParameter cannot be cast to org.eclipse.jdt.core.IType - at org.eclipse.jdt.internal.ui.text.correction.UnresolvedElementsSubProcessor.addNewTypeProposals(UnresolvedElementsSubProcessor.java:913) - at org.eclipse.jdt.internal.ui.text.correction.UnresolvedElementsSubProcessor.getTypeProposals(UnresolvedElementsSubProcessor.java:631) - at org.eclipse.jdt.internal.ui.text.correction.QuickFixProcessor.process(QuickFixProcessor.java:375) - at org.eclipse.jdt.internal.ui.text.correction.QuickFixProcessor.getCorrections(QuickFixProcessor.java:316) - at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor$SafeCorrectionCollector.safeRun(JavaCorrectionProcessor.java:384) - at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor$SafeCorrectionProcessorAccess.run(JavaCorrectionProcessor.java:344) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor$SafeCorrectionProcessorAccess.process(JavaCorrectionProcessor.java:339) - at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor.collectCorrections(JavaCorrectionProcessor.java:474) - at org.eclipse.jdt.internal.ui.text.java.hover.ProblemHover$ProblemInfo.getJavaAnnotationFixes(ProblemHover.java:102) - at org.eclipse.jdt.internal.ui.text.java.hover.ProblemHover$ProblemInfo.getCompletionProposals(ProblemHover.java:76) - at org.eclipse.jdt.internal.ui.text.java.hover.AbstractAnnotationHover$AnnotationInformationControl.deferredCreateContent(AbstractAnnotationHover.java:287) - at org.eclipse.jdt.internal.ui.text.java.hover.AbstractAnnotationHover$AnnotationInformationControl.setInput(AbstractAnnotationHover.java:187) - at org.eclipse.jface.text.AbstractInformationControlManager.internalShowInformationControl(AbstractInformationControlManager.java:1194) - at org.eclipse.jface.text.AbstractInformationControlManager.presentInformation(AbstractInformationControlManager.java:1163) - at org.eclipse.jface.text.AbstractHoverInformationControlManager.presentInformation(AbstractHoverInformationControlManager.java:894) - at org.eclipse.jface.text.TextViewerHoverManager.doPresentInformation(TextViewerHoverManager.java:244) - at org.eclipse.jface.text.TextViewerHoverManager$5.run(TextViewerHoverManager.java:234) - at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) - at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182) - at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4211) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3827) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SESSION 2017-05-29 17:19:29.920 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-29 17:19:36.721 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.jdt.ui 4 10001 2017-05-29 18:00:31.607 -!MESSAGE Internal Error -!STACK 1 -Java Model Exception: Core Exception [code 0] Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -Caused by: org.eclipse.core.runtime.CoreException: Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 1 org.eclipse.jdt.ui 4 0 2017-05-29 18:00:31.608 -!MESSAGE Illegal hierarchy -!SESSION 2017-05-29 21:35:36.875 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-29 21:35:44.958 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-05-30 10:02:31.887 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-30 10:02:58.111 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-05-30 10:24:01.374 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-30 10:24:08.363 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.core.resources 4 2 2017-05-30 10:27:00.358 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.core.resources". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.BinaryExpression.analyseCode(BinaryExpression.java:65) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.analyseCode(ForStatement.java:95) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:125) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.internalAnalyseCode(TypeDeclaration.java:739) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.analyseCode(TypeDeclaration.java:263) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:118) - at org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:873) - at org.eclipse.jdt.internal.compiler.ProcessTaskManager.run(ProcessTaskManager.java:141) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.core.resources 4 75 2017-05-30 10:27:00.483 -!MESSAGE Errors occurred during the build. -!SUBENTRY 1 org.eclipse.jdt.core 4 75 2017-05-30 10:27:00.483 -!MESSAGE Errors running builder 'Java Builder' on project 'UnitParser'. -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.BinaryExpression.analyseCode(BinaryExpression.java:65) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.analyseCode(ForStatement.java:95) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:125) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.internalAnalyseCode(TypeDeclaration.java:739) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.analyseCode(TypeDeclaration.java:263) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:118) - at org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:873) - at org.eclipse.jdt.internal.compiler.ProcessTaskManager.run(ProcessTaskManager.java:141) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.core.resources 4 2 2017-05-30 10:28:32.688 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.core.resources". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.BinaryExpression.analyseCode(BinaryExpression.java:65) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.analyseCode(ForStatement.java:95) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:125) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.internalAnalyseCode(TypeDeclaration.java:739) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.analyseCode(TypeDeclaration.java:263) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:118) - at org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:873) - at org.eclipse.jdt.internal.compiler.ProcessTaskManager.run(ProcessTaskManager.java:141) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.core.resources 4 75 2017-05-30 10:28:32.690 -!MESSAGE Errors occurred during the build. -!SUBENTRY 1 org.eclipse.jdt.core 4 75 2017-05-30 10:28:32.690 -!MESSAGE Errors running builder 'Java Builder' on project 'UnitParser'. -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.BinaryExpression.analyseCode(BinaryExpression.java:65) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.analyseCode(ForStatement.java:95) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:125) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.internalAnalyseCode(TypeDeclaration.java:739) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.analyseCode(TypeDeclaration.java:263) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:118) - at org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:873) - at org.eclipse.jdt.internal.compiler.ProcessTaskManager.run(ProcessTaskManager.java:141) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 10001 2017-05-30 11:21:34.902 -!MESSAGE Internal Error -!STACK 1 -Java Model Exception: Core Exception [code 0] Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -Caused by: org.eclipse.core.runtime.CoreException: Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 1 org.eclipse.jdt.ui 4 0 2017-05-30 11:21:34.903 -!MESSAGE Illegal hierarchy -!SESSION 2017-05-30 13:09:39.087 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-30 13:09:44.844 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-05-30 15:18:51.408 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-30 15:18:58.419 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.jdt.ui 4 10001 2017-05-30 18:03:50.966 -!MESSAGE Internal Error -!STACK 1 -Java Model Exception: Core Exception [code 0] Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -Caused by: org.eclipse.core.runtime.CoreException: Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 1 org.eclipse.jdt.ui 4 0 2017-05-30 18:03:50.967 -!MESSAGE Illegal hierarchy -!SESSION 2017-05-30 18:14:43.952 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-30 18:14:50.864 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.jdt.ui 4 10001 2017-05-30 18:25:16.443 -!MESSAGE Internal Error -!STACK 1 -Java Model Exception: Core Exception [code 0] Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -Caused by: org.eclipse.core.runtime.CoreException: Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 1 org.eclipse.jdt.ui 4 0 2017-05-30 18:25:16.444 -!MESSAGE Illegal hierarchy - -!ENTRY org.eclipse.jdt.ui 4 10001 2017-05-30 18:27:21.425 -!MESSAGE Internal Error -!STACK 1 -Java Model Exception: Core Exception [code 0] Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -Caused by: org.eclipse.core.runtime.CoreException: Illegal hierarchy - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.findMatchingSuperTypeSignature(LazyGenericTypeProposal.java:572) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.mapTypeParameterIndex(LazyGenericTypeProposal.java:532) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.computeTypeArgumentProposals(LazyGenericTypeProposal.java:351) - at org.eclipse.jdt.internal.ui.text.java.LazyGenericTypeProposal.apply(LazyGenericTypeProposal.java:225) - at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.apply(AbstractJavaCompletionProposal.java:519) - at org.eclipse.jdt.internal.ui.text.java.LazyJavaCompletionProposal.apply(LazyJavaCompletionProposal.java:443) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:989) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertSelectedProposalWithMask(CompletionProposalPopup.java:938) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$27(CompletionProposalPopup.java:934) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$5.widgetDefaultSelected(CompletionProposalPopup.java:679) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:120) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 1 org.eclipse.jdt.ui 4 0 2017-05-30 18:27:21.426 -!MESSAGE Illegal hierarchy -!SESSION 2017-05-30 21:15:48.643 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-30 21:15:55.290 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-30 21:26:07.992 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.EqualExpression.resolveType(EqualExpression.java:827) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolveTypeExpecting(Expression.java:1056) - at org.eclipse.jdt.internal.compiler.ast.IfStatement.resolve(IfStatement.java:273) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-30 21:26:08.002 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.EqualExpression.resolveType(EqualExpression.java:827) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolveTypeExpecting(Expression.java:1056) - at org.eclipse.jdt.internal.compiler.ast.IfStatement.resolve(IfStatement.java:273) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-30 21:26:08.095 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.EqualExpression.resolveType(EqualExpression.java:827) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolveTypeExpecting(Expression.java:1056) - at org.eclipse.jdt.internal.compiler.ast.IfStatement.resolve(IfStatement.java:273) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-30 21:26:08.098 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.EqualExpression.resolveType(EqualExpression.java:827) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolveTypeExpecting(Expression.java:1056) - at org.eclipse.jdt.internal.compiler.ast.IfStatement.resolve(IfStatement.java:273) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) -!SESSION 2017-05-31 10:07:17.384 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-31 10:07:43.640 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-05-31 15:34:07.553 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-31 15:34:14.552 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-05-31 17:45:11.958 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-31 17:45:17.512 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-05-31 22:55:31.033 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-05-31 22:55:37.634 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-01 15:45:27.022 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-01 15:45:37.943 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-01 16:42:29.042 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-01 16:42:35.534 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-01 16:55:48.373 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-01 16:55:54.505 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.jdt.core 4 4 2017-06-01 18:38:29.011 -!MESSAGE Exception occurred during problem detection: ------------------------------------ SOURCE BEGIN ------------------------------------- -package InternalUnitParser.CSharpAdaptation; - -import java.util.ArrayList; - -public class CSharpOther -{ - public static ArrayList StringToCharacters(String input) - { - ArrayList chars = new ArrayList(); - if (input == null) return chars; - - for (char item: input.toCharArray()) - { - chars.add(item); - } - - return chars; - } - - public static String StringJoin(String separator, String[] parts, int start, int length) - { - if (parts == null) return null; - if (parts.length == 1) return parts[0].toString(); - - String outString = parts[0].toString(); - - for (int i = 1; i < parts.length; i++) - { - outString += separator + parts[i].toString(); - } - - return outString; - } - - public static String StringJoin(String separator, Character[] parts) - { - - } - - static String StringInternal(String separator, String[] parts, Character[] parts2, int start, int length) - { - if (parts == null && parts2 == null) return null; - if (parts.length == 1) return parts[0].toString(); - - int total = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - - String outString = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - for (int i = 1; i < total; i++) - { - outString += StringInternalBit(String[] parts, Character[] parts2, int i, String separator) - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } - - return outString; - } - - static String StringInternalBit(String[] parts, Character[] parts2, int i, String separator) - { - return separator + - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:29.031 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:29.031 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:29.031 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:29.041 -!MESSAGE Error in JDT Core during reconcile -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:29.041 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:29.242 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:29.252 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:35.630 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:35.640 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:36.898 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:36.908 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-06-01 18:38:40.081 -!MESSAGE Exception occurred during problem detection: ------------------------------------ SOURCE BEGIN ------------------------------------- -package InternalUnitParser.CSharpAdaptation; - -import java.util.ArrayList; - -public class CSharpOther -{ - public static ArrayList StringToCharacters(String input) - { - ArrayList chars = new ArrayList(); - if (input == null) return chars; - - for (char item: input.toCharArray()) - { - chars.add(item); - } - - return chars; - } - - public static String StringJoin(String separator, String[] parts, int start, int length) - { - if (parts == null) return null; - if (parts.length == 1) return parts[0].toString(); - - String outString = parts[0].toString(); - - for (int i = 1; i < parts.length; i++) - { - outString += separator + parts[i].toString(); - } - - return outString; - } - - public static String StringJoin(String separator, Character[] parts) - { - - } - - static String StringInternal(String separator, String[] parts, Character[] parts2, int start, int length) - { - if (parts == null && parts2 == null) return null; - if (parts.length == 1) return parts[0].toString(); - - int total = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - - String outString = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - for (int i = 1; i < total; i++) - { - outString += StringInternalBit - ( - String[] parts, Character[] parts2, int i, String separator) - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } - - return outString; - } - - static String StringInternalBit(String[] parts, Character[] parts2, int i, String separator) - { - return separator + - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:40.091 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:40.091 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:40.091 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:40.091 -!MESSAGE Error in JDT Core during reconcile -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:40.091 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:40.101 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:40.101 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:40.101 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:40.101 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:42.110 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:42.110 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:42.230 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:42.230 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.core 4 4 2017-06-01 18:38:43.604 -!MESSAGE Exception occurred during problem detection: ------------------------------------ SOURCE BEGIN ------------------------------------- -package InternalUnitParser.CSharpAdaptation; - -import java.util.ArrayList; - -public class CSharpOther -{ - public static ArrayList StringToCharacters(String input) - { - ArrayList chars = new ArrayList(); - if (input == null) return chars; - - for (char item: input.toCharArray()) - { - chars.add(item); - } - - return chars; - } - - public static String StringJoin(String separator, String[] parts, int start, int length) - { - if (parts == null) return null; - if (parts.length == 1) return parts[0].toString(); - - String outString = parts[0].toString(); - - for (int i = 1; i < parts.length; i++) - { - outString += separator + parts[i].toString(); - } - - return outString; - } - - public static String StringJoin(String separator, Character[] parts) - { - - } - - static String StringInternal(String separator, String[] parts, Character[] parts2, int start, int length) - { - if (parts == null && parts2 == null) return null; - if (parts.length == 1) return parts[0].toString(); - - int total = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - - String outString = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - for (int i = 1; i < total; i++) - { - outString += StringInternalBit - ( - String[] parts, Character[] parts2, int i, String separator - ) - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } - - return outString; - } - - static String StringInternalBit(String[] parts, Character[] parts2, int i, String separator) - { - return separator + - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:43.604 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:43.604 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:43.604 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:43.614 -!MESSAGE Error in JDT Core during reconcile -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:43.614 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:43.614 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:43.624 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:47.463 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:47.463 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:47.583 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:47.583 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.core 4 4 2017-06-01 18:38:49.140 -!MESSAGE Exception occurred during problem detection: ------------------------------------ SOURCE BEGIN ------------------------------------- -package InternalUnitParser.CSharpAdaptation; - -import java.util.ArrayList; - -public class CSharpOther -{ - public static ArrayList StringToCharacters(String input) - { - ArrayList chars = new ArrayList(); - if (input == null) return chars; - - for (char item: input.toCharArray()) - { - chars.add(item); - } - - return chars; - } - - public static String StringJoin(String separator, String[] parts, int start, int length) - { - if (parts == null) return null; - if (parts.length == 1) return parts[0].toString(); - - String outString = parts[0].toString(); - - for (int i = 1; i < parts.length; i++) - { - outString += separator + parts[i].toString(); - } - - return outString; - } - - public static String StringJoin(String separator, Character[] parts) - { - - } - - static String StringInternal(String separator, String[] parts, Character[] parts2, int start, int length) - { - if (parts == null && parts2 == null) return null; - if (parts.length == 1) return parts[0].toString(); - - int total = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - - String outString = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - for (int i = 1; i < total; i++) - { - outString += StringInternalBit - ( - String[] parts, Character[] parts2, i, String separator - ) - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } - - return outString; - } - - static String StringInternalBit(String[] parts, Character[] parts2, int i, String separator) - { - return separator + - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:49.140 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:49.140 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:49.140 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:49.150 -!MESSAGE Error in JDT Core during reconcile -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:49.150 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:49.210 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:49.210 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:49.340 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:49.340 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.core 4 4 2017-06-01 18:38:55.176 -!MESSAGE Exception occurred during problem detection: ------------------------------------ SOURCE BEGIN ------------------------------------- -package InternalUnitParser.CSharpAdaptation; - -import java.util.ArrayList; - -public class CSharpOther -{ - public static ArrayList StringToCharacters(String input) - { - ArrayList chars = new ArrayList(); - if (input == null) return chars; - - for (char item: input.toCharArray()) - { - chars.add(item); - } - - return chars; - } - - public static String StringJoin(String separator, String[] parts, int start, int length) - { - if (parts == null) return null; - if (parts.length == 1) return parts[0].toString(); - - String outString = parts[0].toString(); - - for (int i = 1; i < parts.length; i++) - { - outString += separator + parts[i].toString(); - } - - return outString; - } - - public static String StringJoin(String separator, Character[] parts) - { - - } - - static String StringInternal(String separator, String[] parts, Character[] parts2, int start, int length) - { - if (parts == null && parts2 == null) return null; - if (parts.length == 1) return parts[0].toString(); - - int total = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - - String outString = - ( - parts == null ? parts2[0].toString() : parts[0] - ); - - for (int i = 1; i < total; i++) - { - outString += StringInternalBit - ( - String[] parts, parts2, i, String separator - ) - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } - - return outString; - } - - static String StringInternalBit(String[] parts, Character[] parts2, int i, String separator) - { - return separator + - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:55.176 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:55.176 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:55.176 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:55.176 -!MESSAGE Error in JDT Core during reconcile -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:38:55.176 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:55.186 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:55.186 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:55.186 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:55.206 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:56.169 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:56.179 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:38:56.289 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:38:56.289 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.findMethodBinding(MessageSend.java:914) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:729) - at org.eclipse.jdt.internal.compiler.ast.CompoundAssignment.resolveType(CompoundAssignment.java:132) - at org.eclipse.jdt.internal.compiler.ast.Expression.resolve(Expression.java:1026) - at org.eclipse.jdt.internal.compiler.ast.Block.resolve(Block.java:117) - at org.eclipse.jdt.internal.compiler.ast.ForStatement.resolve(ForStatement.java:404) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) diff --git a/all_code/.metadata/.bak_1.log b/all_code/.metadata/.bak_1.log deleted file mode 100644 index 16c6e81..0000000 --- a/all_code/.metadata/.bak_1.log +++ /dev/null @@ -1,23419 +0,0 @@ -!SESSION 2017-05-27 19:54:17.091 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -This is a continuation of log file C:\Users\Alvaro\Desktop\workspace\.metadata\.bak_0.log -Created Time: 2017-05-27 19:57:20.189 - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:57:20.189 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:57:20.189 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:57:25.314 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:57:25.315 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:57:25.315 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:57:25.347 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:57:25.348 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:57:25.349 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:57:32.300 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:57:32.301 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:57:32.302 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:57:32.887 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:57:32.890 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:57:32.891 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:57:34.081 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:57:34.082 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:57:34.083 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:57:56.573 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} - } - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:57:56.575 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:57:56.575 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:57:56.603 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} - } - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:57:56.604 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:57:56.604 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:15.879 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:15.880 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:15.881 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:16.027 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:16.028 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:16.029 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:17.685 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:17.686 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:17.686 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:20.660 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:20.661 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:20.662 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:21.593 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:21.594 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:21.594 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:22.118 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:22.120 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:22.121 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:23.418 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:23.419 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:23.419 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:23.644 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:23.646 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:23.647 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:25.953 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:25.955 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:25.955 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:28.488 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:28.489 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:28.490 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:32.025 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:32.026 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:32.026 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:32.049 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:32.050 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:32.051 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:34.080 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:34.081 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:34.082 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:34.139 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:34.140 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:34.140 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:36.125 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:36.126 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:36.127 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:36.156 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:36.163 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:36.165 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:39.165 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:39.166 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:39.166 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:39.188 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:39.189 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:39.190 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:53.222 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:53.223 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:53.224 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 19:58:53.523 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - else - { - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - return new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - } - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 19:58:53.524 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 19:58:53.525 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:02:58.166 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:02:58.168 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:02:58.169 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:02:58.197 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }}; - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:02:58.198 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:02:58.198 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:02:59.206 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:02:59.207 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:02:59.207 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:02:59.225 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:02:59.226 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:02:59.227 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:02:59.776 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:02:59.777 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:02:59.777 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:01.081 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:01.086 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:01.086 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:01.145 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoveredASTNode(JavadocHover.java:897) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getInfoText(JavadocHover.java:763) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo(JavadocHover.java:712) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.internalGetHoverInfo(JavadocHover.java:635) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo2(JavadocHover.java:627) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:01.146 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoveredASTNode(JavadocHover.java:897) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getInfoText(JavadocHover.java:763) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo(JavadocHover.java:712) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.internalGetHoverInfo(JavadocHover.java:635) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo2(JavadocHover.java:627) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:01.146 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoveredASTNode(JavadocHover.java:897) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getInfoText(JavadocHover.java:763) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo(JavadocHover.java:712) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.internalGetHoverInfo(JavadocHover.java:635) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo2(JavadocHover.java:627) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:03.233 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:03.234 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) diff --git a/all_code/.metadata/.bak_2.log b/all_code/.metadata/.bak_2.log deleted file mode 100644 index 0c8f6c0..0000000 --- a/all_code/.metadata/.bak_2.log +++ /dev/null @@ -1,23728 +0,0 @@ -!SESSION 2017-05-27 19:54:17.091 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -This is a continuation of log file C:\Users\Alvaro\Desktop\workspace\.metadata\.bak_1.log -Created Time: 2017-05-27 20:03:03.235 - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:03.235 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:03.263 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:03.264 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:03.264 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:07.352 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:07.353 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:07.353 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:08.769 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:08.770 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:08.771 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:08.793 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:08.793 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:08.794 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:11.288 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:11.289 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:11.290 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:207) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:11.309 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:11.310 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:11.310 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.getOverrideIndicators(OverrideIndicatorLabelDecorator.java:157) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.computeAdornmentFlags(OverrideIndicatorLabelDecorator.java:132) - at org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator.decorate(OverrideIndicatorLabelDecorator.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorDefinition.decorate(LightweightDecoratorDefinition.java:260) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager$LightweightRunnable.run(LightweightDecoratorManager.java:100) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.decorate(LightweightDecoratorManager.java:383) - at org.eclipse.ui.internal.decorators.LightweightDecoratorManager.getDecorations(LightweightDecoratorManager.java:365) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.ensureResultCached(DecorationScheduler.java:367) - at org.eclipse.ui.internal.decorators.DecorationScheduler$1.run(DecorationScheduler.java:327) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:14.000 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:14.001 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:14.001 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:22.894 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:22.895 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:22.896 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:23.617 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:23.618 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:23.619 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:40.996 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:40.997 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:40.997 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:41.744 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:41.745 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:41.745 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:42.575 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:42.576 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:42.577 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:45.077 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:45.078 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:45.078 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:45.099 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoveredASTNode(JavadocHover.java:897) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getInfoText(JavadocHover.java:763) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo(JavadocHover.java:712) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.internalGetHoverInfo(JavadocHover.java:635) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo2(JavadocHover.java:627) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:45.099 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoveredASTNode(JavadocHover.java:897) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getInfoText(JavadocHover.java:763) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo(JavadocHover.java:712) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.internalGetHoverInfo(JavadocHover.java:635) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo2(JavadocHover.java:627) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:45.100 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoveredASTNode(JavadocHover.java:897) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getInfoText(JavadocHover.java:763) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo(JavadocHover.java:712) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.internalGetHoverInfo(JavadocHover.java:635) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo2(JavadocHover.java:627) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:49.876 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:49.877 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:49.877 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:49.901 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoveredASTNode(JavadocHover.java:897) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getInfoText(JavadocHover.java:763) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo(JavadocHover.java:712) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.internalGetHoverInfo(JavadocHover.java:635) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo2(JavadocHover.java:627) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:49.903 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoveredASTNode(JavadocHover.java:897) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getInfoText(JavadocHover.java:763) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo(JavadocHover.java:712) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.internalGetHoverInfo(JavadocHover.java:635) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo2(JavadocHover.java:627) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:49.903 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoveredASTNode(JavadocHover.java:897) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getInfoText(JavadocHover.java:763) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo(JavadocHover.java:712) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.internalGetHoverInfo(JavadocHover.java:635) - at org.eclipse.jdt.internal.ui.text.java.hover.JavadocHover.getHoverInfo2(JavadocHover.java:627) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:56.638 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:56.639 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:56.640 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:03:58.347 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:03:58.349 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:03:58.351 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:07.397 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:07.398 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:07.398 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:07.418 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:07.419 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:07.419 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:18.135 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:18.136 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:18.137 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:19.428 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:19.429 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:19.430 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:19.551 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:19.552 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:19.553 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:23.202 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if(iswrong) - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:23.203 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:23.204 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:24.814 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if(iswrong) - { - } - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:24.815 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:24.816 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:25.031 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if(iswrong) - { - } - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:25.033 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:25.033 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:27.066 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if(iswrong) - { - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:27.068 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:27.068 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:27.669 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if(iswrong) - { - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:27.670 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:27.671 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:28.322 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if(iswrong) - { - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:28.323 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:28.324 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:31.100 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if(isWrong) - { - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:31.101 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:31.101 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:32.637 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:32.638 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:32.638 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:32.972 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:32.973 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:32.974 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:36.251 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:36.252 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:36.252 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:36.794 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:36.795 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:36.796 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:37.337 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:37.338 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:37.338 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:39.167 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) diff --git a/all_code/.metadata/.bak_3.log b/all_code/.metadata/.bak_3.log deleted file mode 100644 index 4c9a3eb..0000000 --- a/all_code/.metadata/.bak_3.log +++ /dev/null @@ -1,23527 +0,0 @@ -!SESSION 2017-05-27 19:54:17.091 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -This is a continuation of log file C:\Users\Alvaro\Desktop\workspace\.metadata\.bak_2.log -Created Time: 2017-05-27 20:04:39.170 - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:39.170 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:39.170 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:39.192 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:39.193 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:39.193 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:40.334 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:40.335 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:40.335 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:41.699 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:41.700 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:41.703 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:45.239 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:45.240 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:45.241 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:45.326 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:45.327 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:45.327 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:46.277 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:46.278 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:46.278 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:48.273 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:48.274 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:48.275 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:48.323 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:48.324 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:48.324 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:50.812 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - te. - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:50.813 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:50.813 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:50.845 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - te. - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:50.846 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:50.847 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:52.875 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp. - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:52.876 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:52.876 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:52.905 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp. - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:52.906 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:52.906 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:57.946 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp. - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:57.947 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:57.947 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:58.061 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp. - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:58.063 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:58.063 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:04:58.547 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp. - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:04:58.549 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:04:58.549 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:00.412 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:00.413 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:00.413 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:00.461 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:00.462 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:00.462 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:02.535 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:02.536 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:02.536 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:03.945 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:03.946 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:03.947 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:04.142 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:04.143 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:04.144 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:05.983 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - } - - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:05.984 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:05.985 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:06.976 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:06.977 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:06.977 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:06.997 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:06.999 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:06.999 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:11.545 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:11.546 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:11.547 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:11.831 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:11.833 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:11.833 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:16.870 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:16.872 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:16.872 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:16.973 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:16.974 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:16.974 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:17.506 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:17.507 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:17.507 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.getClipboardData(ClipboardOperationAction.java:430) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithImportsOperation(ClipboardOperationAction.java:357) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOperation(ClipboardOperationAction.java:317) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run(ClipboardOperationAction.java:265) - at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) - at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run(ClipboardOperationAction.java:262) - at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) - at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:118) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) - at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1270) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1078) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1130) - at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1126) - at org.eclipse.swt.widgets.Widget.wmChar(Widget.java:1547) - at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:4918) - at org.eclipse.swt.widgets.Canvas.WM_CHAR(Canvas.java:364) - at org.eclipse.swt.widgets.Control.windowProc(Control.java:4799) - at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359) - at org.eclipse.swt.widgets.Display.windowProc(Display.java:5110) - at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) - at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3822) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:18.769 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:18.770 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:18.770 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:24.619 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:24.620 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:24.621 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:28.291 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - UnitInfo temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:28.292 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:28.292 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:29.150 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:29.150 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:29.151 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:29.175 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:29.175 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:29.176 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:29.192 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-05-27 20:05:29.193 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-05-27 20:05:29.193 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.core 4 4 2017-05-27 20:05:29.216 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -public class OperationsManaged -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, new UnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - new UnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = InternalMethods.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return new UnitInfo(firstInfo) - {{ - Error = new ErrorInfo(errorType); - }}; - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - UnitInfo[] normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static UnitInfo[] GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - UnitInfo[] operands2 = new UnitInfo[] - { - new UnitInfo(firstInfo), new UnitInfo(secondInfo) - }; - - if (operands2[0].BaseTenExponent != operands2[1].BaseTenExponent || operands2[0].Prefix.Factor != operands2[1].Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - operands2 = AdaptNormalisedValuesForAddition - ( - new UnitInfo[] - { - NormaliseUnitInfo(operands2[0]), - NormaliseUnitInfo(operands2[1]) - }, - operation - ); - } - - return operands2; - } - - static UnitInfo[] AdaptNormalisedValuesForAddition(UnitInfo[] unitInfos2, Operations operation) - { - if (unitInfos2[0].BaseTenExponent == unitInfos2[1].BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2[0].BaseTenExponent > unitInfos2[1].BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2[bigSmallI[0]].Value = big2.Value; - unitInfos2[bigSmallI[0]].BaseTenExponent = unitInfos2[bigSmallI[1]].BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static UnitInfo[] TooBigGapAddition(UnitInfo[] unitInfos2, int[] bigSmallI, Operations operation) - { - UnitInfo[] outInfos = new UnitInfo[] - { - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - new UnitInfo(unitInfos2[0]) - {{ - Value = unitInfos2[bigSmallI[0]].Value; - BaseTenExponent = unitInfos2[bigSmallI[0]].BaseTenExponent; - }} - }; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos[0].Value = -1.0 * outInfos[0].Value; - } - - if (outInfos[0].Unit == Units.Unitless) - { - outInfos[0].Unit = unitInfos2[bigSmallI[1]].Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(UnitInfo[] unitInfos2, Integer[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2[bigSmallI[0]].BaseTenExponent - unitInfos2[bigSmallI[1]].BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2[bigSmallI[0]].Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2[0].Value, unitInfos2[1].Value, operation - ) - ); - - UnitInfo temp = null; - if (isWrong) - { - temp = new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }}; - - temp.Error = new ErrorInfo(ErrorTypes.InvalidOperation); - - } - - - return temp; - - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new UnitInfo(unitInfos2[0]) - {{ - Error = new ErrorInfo(ErrorTypes.InvalidOperation); - }} : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new UnitInfo(unitInfos2[bigSmallI[0]]) - {{ - Value = big2.Value; - }} - ) - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new UnitInfo[] - { - NormaliseUnitInfo(firstInfo), - NormaliseUnitInfo(secondInfo) - }, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(new UnitInfo(baseValue), exponent); - } - - static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = new UnitInfo(baseInfo); - - for (int i = 1; i < Math.Abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(new UnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.Length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos[0] : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, UnitInfo[] normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos[0], normalisedInfos[1], operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - }; - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - new UnitInfo(firstValue), new UnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, new UnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return new UnitInfo(firstInfo) { Value = 0.0 }; - } - } - - UnitInfo outInfo = new UnitInfo(firstInfo); - UnitInfo firstInfo0 = new UnitInfo(firstInfo); - UnitInfo secondInfo0 = new UnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - return - ( - new UnitInfo(outInfo) - { - Error = new ErrorInfo(ErrorTypes.NumericError) - } - ); - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.Abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch - { - //Very unlikely scenario on account of the fact that Math.Abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - outInfo = OperationValuesManageError - ( - new UnitInfo(outInfo) - { - Value = secondInfo2.Value, - BaseTenExponent = 0 - }, - new UnitInfo() - { - Value = outInfo.Value, - BaseTenExponent = outInfo.BaseTenExponent - }, - operation - ); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.Abs(value); - return FromValueToBaseTenExponent - ( - new UnitInfo(value), Math.Abs(value), false - ); - } - - static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = new UnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = Math.Sign(outInfo.Value); - double absValue = Math.Abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= MaxValueDec / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= MinValueDec * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = new UnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.Abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1.0 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.Abs(value); - } - - return outInfo; - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision = false) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MAIN_VALUE - val2)) ? - new UnitInfo(info, ErrorTypes.NumericError) : new UnitInfo(info){{ BaseTenExponent = (int)(val1 + val2); }} - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:425) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:295) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1216) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) diff --git a/all_code/.metadata/.lock b/all_code/.metadata/.lock deleted file mode 100644 index e69de29..0000000 diff --git a/all_code/.metadata/.log b/all_code/.metadata/.log deleted file mode 100644 index 3c62884..0000000 --- a/all_code/.metadata/.log +++ /dev/null @@ -1,3023 +0,0 @@ -!SESSION 2017-06-01 16:55:48.373 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -This is a continuation of log file C:\Users\Alvaro\Desktop\workspace\.metadata\.bak_0.log -Created Time: 2017-06-01 18:41:31.268 - -!ENTRY org.eclipse.jdt.core 4 4 2017-06-01 18:41:31.268 -!MESSAGE Exception occurred during problem detection: ------------------------------------ SOURCE BEGIN ------------------------------------- -package InternalUnitParser.CSharpAdaptation; - -import java.util.ArrayList; - -public class CSharpOther -{ - public static ArrayList StringToCharacters(String input) - { - ArrayList chars = new ArrayList(); - if (input == null) return chars; - - for (char item: input.toCharArray()) - { - chars.add(item); - } - - return chars; - } - - public static String StringJoin(String separator, String[] parts, int start, int length) - { - if (parts == null) return null; - if (parts.length == 1) return parts[0].toString(); - - String outString = parts[0].toString(); - - for (int i = 1; i < parts.length; i++) - { - outString += separator + parts[i].toString(); - } - - return outString; - } - - public static String StringJoin(String separator, Character[] parts) - { - return StringInternal(String separator, String[] parts, Character[] parts2, int start, int length) - } - - static String StringInternal(String separator, String[] parts, Character[] parts2, int start, int length) - { - if (parts == null && parts2 == null) return null; - - int total = - ( - parts == null ? parts2.length : parts.length - ); - if (total == 1) - { - return - ( - parts == null ? parts2[0].toString() : parts[0] - ); - } - - String outString = StringInternalBit - ( - parts, parts2, 0, "" - ); - - for (int i = 1; i < total; i++) - { - outString += StringInternalBit - ( - parts, parts2, i, separator - ); - } - - return outString; - } - - static String StringInternalBit(String[] parts, Character[] parts2, int i, String separator) - { - return separator + - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:41:31.268 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:41:31.268 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:41:31.268 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:41:31.268 -!MESSAGE Error in JDT Core during reconcile -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:41:31.268 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:41:31.318 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:41:31.318 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:41:33.425 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:41:33.425 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.internalGetHoverInfo(NLSStringHover.java:137) - at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo2(NLSStringHover.java:116) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:164) - at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:130) - at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:86) - at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:165) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:41:33.495 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:41:33.495 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.core 4 4 2017-06-01 18:41:38.293 -!MESSAGE Exception occurred during problem detection: ------------------------------------ SOURCE BEGIN ------------------------------------- -package InternalUnitParser.CSharpAdaptation; - -import java.util.ArrayList; - -public class CSharpOther -{ - public static ArrayList StringToCharacters(String input) - { - ArrayList chars = new ArrayList(); - if (input == null) return chars; - - for (char item: input.toCharArray()) - { - chars.add(item); - } - - return chars; - } - - public static String StringJoin(String separator, String[] parts, int start, int length) - { - if (parts == null) return null; - if (parts.length == 1) return parts[0].toString(); - - String outString = parts[0].toString(); - - for (int i = 1; i < parts.length; i++) - { - outString += separator + parts[i].toString(); - } - - return outString; - } - - public static String StringJoin(String separator, Character[] parts) - { - return StringInternal - ( - separator, String[] parts, Character[] parts2, int start, int length) - } - - static String StringInternal(String separator, String[] parts, Character[] parts2, int start, int length) - { - if (parts == null && parts2 == null) return null; - - int total = - ( - parts == null ? parts2.length : parts.length - ); - if (total == 1) - { - return - ( - parts == null ? parts2[0].toString() : parts[0] - ); - } - - String outString = StringInternalBit - ( - parts, parts2, 0, "" - ); - - for (int i = 1; i < total; i++) - { - outString += StringInternalBit - ( - parts, parts2, i, separator - ); - } - - return outString; - } - - static String StringInternalBit(String[] parts, Character[] parts2, int i, String separator) - { - return separator + - ( - parts == null ? parts2[i].toString() : parts[i] - ); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:41:38.293 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:41:38.293 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:41:38.293 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:41:38.293 -!MESSAGE Error in JDT Core during reconcile -!STACK 1 -Java Model Exception: java.lang.NullPointerException - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:249) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - ... 19 more -Caused by: java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SUBENTRY 1 org.eclipse.jdt.core 4 1005 2017-06-01 18:41:38.303 -!MESSAGE java.lang.NullPointerException -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1030) - at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:197) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:194) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:41:38.303 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:41:38.303 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:476) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:41:38.373 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:41:38.373 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.recommenders.rcp.utils.JdtUtils.findAstNodeFromEditorSelection(JdtUtils.java:669) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.handleSelectionInEditor(JavaElementSelectionService.java:110) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService.access$1(JavaElementSelectionService.java:105) - at org.eclipse.recommenders.internal.rcp.JavaElementSelectionService$1.run(JavaElementSelectionService.java:82) - at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) - at java.util.concurrent.FutureTask.run(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) - at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-01 18:41:38.403 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-01 18:41:38.403 -!MESSAGE Error in JDT Core during AST creation -!STACK 0 -java.lang.NullPointerException - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.copy(ReferenceExpression.java:141) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.cachedResolvedCopy(ReferenceExpression.java:819) - at org.eclipse.jdt.internal.compiler.ast.ReferenceExpression.isCompatibleWith(ReferenceExpression.java:1085) - at org.eclipse.jdt.internal.compiler.lookup.PolyTypeBinding.isCompatibleWith(PolyTypeBinding.java:37) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4790) - at org.eclipse.jdt.internal.compiler.lookup.Scope.parameterCompatibilityLevel(Scope.java:4757) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:773) - at org.eclipse.jdt.internal.compiler.lookup.Scope.computeCompatibleMethod(Scope.java:700) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod0(Scope.java:1656) - at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1557) - at org.eclipse.jdt.internal.compiler.lookup.Scope.getImplicitMethod(Scope.java:2524) - at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:696) - at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.resolve(ReturnStatement.java:342) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:634) - at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:306) - at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:544) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1195) - at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1308) - at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:593) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:1218) - at org.eclipse.jdt.core.dom.CompilationUnitResolver.resolve(CompilationUnitResolver.java:692) - at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1190) - at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:812) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider$1.run(ASTProvider.java:551) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.createAST(ASTProvider.java:543) - at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:486) - at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:128) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:173) - at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$3.run(SelectionListenerWithASTManager.java:158) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) -!SESSION 2017-06-01 20:37:48.599 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-01 20:37:54.887 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-02 12:26:02.678 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-02 12:26:19.293 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.recommenders.subwords.rcp 4 1 2017-06-02 13:53:27.465 -!MESSAGE Exception during code completion -!STACK 0 -org.eclipse.core.runtime.OperationCanceledException - at org.eclipse.jdt.internal.codeassist.CompletionEngine.checkCancel(CompletionEngine.java:1688) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.completionOnSingleNameReference(CompletionEngine.java:3298) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:1718) - at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:1944) - at org.eclipse.jdt.internal.core.Openable.codeComplete(Openable.java:131) - at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:357) - at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:345) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.computeProposals(SubwordsSessionProcessor.java:338) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.getNewProposals(SubwordsSessionProcessor.java:227) - at org.eclipse.recommenders.internal.subwords.rcp.SubwordsSessionProcessor.initializeContext(SubwordsSessionProcessor.java:167) - at org.eclipse.recommenders.completion.rcp.processable.IntelligentCompletionProposalComputer.fireInitializeContext(IntelligentCompletionProposalComputer.java:292) - at org.eclipse.recommenders.completion.rcp.processable.IntelligentCompletionProposalComputer.computeCompletionProposals(IntelligentCompletionProposalComputer.java:169) - at org.eclipse.jdt.internal.ui.text.java.CompletionProposalComputerDescriptor.computeCompletionProposals(CompletionProposalComputerDescriptor.java:333) - at org.eclipse.jdt.internal.ui.text.java.CompletionProposalCategory.computeCompletionProposals(CompletionProposalCategory.java:337) - at org.eclipse.jdt.internal.ui.text.java.ContentAssistProcessor.collectProposals(ContentAssistProcessor.java:331) - at org.eclipse.jdt.internal.ui.text.java.ContentAssistProcessor.computeCompletionProposals(ContentAssistProcessor.java:288) - at org.eclipse.jface.text.contentassist.ContentAssistant$3.run(ContentAssistant.java:1931) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals(ContentAssistant.java:1928) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals(CompletionProposalPopup.java:565) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeFilteredProposals(CompletionProposalPopup.java:1523) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$4(CompletionProposalPopup.java:1512) - at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:362) - at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) - at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182) - at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4211) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3827) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) - -!ENTRY org.eclipse.jdt.ui 2 0 2017-06-02 13:53:27.496 -!MESSAGE The 'org.eclipse.recommenders.completion.rcp.javaCompletionProposalComputer.intelligent' proposal computer from the 'org.eclipse.recommenders.completion.rcp' plug-in did not complete normally. The extension took too long to return from the 'computeCompletionProposals()' operation. - -!ENTRY org.eclipse.recommenders.rcp 4 18 2017-06-02 14:02:39.217 -!MESSAGE Failed to resolve selection in ‘=UnitParser/src_Internal Git > Confirmations and Warnings preference page. -!SESSION 2017-06-02 18:05:37.894 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-02 18:05:44.026 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-02 20:08:02.476 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-02 20:08:08.704 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-02 21:08:35.980 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-02 21:08:42.096 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-02 21:31:17.408 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-02 21:31:23.571 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-02 21:55:27.771 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-02 21:55:33.825 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 11:12:05.004 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.jdt.core 4 0 2017-06-03 11:12:13.913 -!MESSAGE Invalid ZIP archive: C:\Users\Alvaro\Desktop\UnitParser.jar - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 11:12:14.053 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 11:15:51.649 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 11:15:57.905 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.jdt.core 4 4 2017-06-03 11:41:32.301 -!MESSAGE Exception occurred during compilation unit conversion: ------------------------------------ SOURCE BEGIN ------------------------------------- -package test0; - -import java.util.ArrayList; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -public class Main -{ - public static void main(String[] args) - { - ArrayList chars0 = new ArrayList() - ´{; - String[] chars = StringJoinChars - ( - "", TakeWhile - ( - StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x == 'e' || - x == '-' || x == '+' || x == '.' || x == ',' - ) - ); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Select(input, (Function)filter); - - for (X item: input) - { - if (!input2.contains(item)) return output; - - output.add(item); - } - - return output; - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } -} - ------------------------------------ SOURCE END ------------------------------------- -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.convertToFieldDeclaration(ASTConverter.java:3218) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:438) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 2 2017-06-03 11:41:32.348 -!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jdt.ui". -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.convertToFieldDeclaration(ASTConverter.java:3218) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:438) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) - -!ENTRY org.eclipse.jdt.ui 4 0 2017-06-03 11:41:32.348 -!MESSAGE Error in JDT Core during reconcile -!STACK 0 -java.lang.IllegalArgumentException - at org.eclipse.jdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2845) - at org.eclipse.jdt.core.dom.ASTConverter.convertToFieldDeclaration(ASTConverter.java:3218) - at org.eclipse.jdt.core.dom.ASTConverter.checkAndAddMultipleFieldDeclaration(ASTConverter.java:438) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:327) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2518) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1697) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2758) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:639) - at org.eclipse.jdt.core.dom.ASTConverter.buildBodyDeclarations(ASTConverter.java:195) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2965) - at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:1374) - at org.eclipse.jdt.core.dom.AST.convertCompilationUnit(AST.java:270) - at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure(CompilationUnit.java:202) - at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:259) - at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579) - at org.eclipse.jdt.internal.core.CompilationUnit.makeConsistent(CompilationUnit.java:1085) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:171) - at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90) - at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:724) - at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:790) - at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1250) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:128) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:110) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:90) - at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87) - at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:154) - at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:89) - at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104) - at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:73) - at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207) -!SESSION 2017-06-03 12:35:27.600 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 12:35:33.623 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 14:50:44.370 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 14:50:50.889 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 15:51:25.627 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 15:51:31.900 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 16:51:32.096 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 16:51:38.181 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 18:01:26.124 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 18:01:32.849 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 19:17:45.448 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 19:17:52.279 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.recommenders.rcp 4 18 2017-06-03 20:05:01.991 -!MESSAGE Failed to resolve selection in ‘=UnitParser/src_Internal Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 20:47:10.818 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 20:47:17.137 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 21:09:05.231 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 21:09:12.299 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-03 22:16:13.197 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-03 22:16:19.964 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.jdt.ui 4 10001 2017-06-03 22:39:38.737 -!MESSAGE Internal Error -!STACK 1 -org.eclipse.core.runtime.CoreException: Launch configuration Testing references non-existing project testing. - at org.eclipse.jdt.launching.JavaRuntime.abort(JavaRuntime.java:1408) - at org.eclipse.jdt.launching.JavaRuntime.getJavaProject(JavaRuntime.java:1283) - at org.eclipse.jdt.launching.StandardClasspathProvider.computeUnresolvedClasspath(StandardClasspathProvider.java:40) - at org.eclipse.jdt.launching.JavaRuntime.computeUnresolvedRuntimeClasspath(JavaRuntime.java:1246) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizardPage.getClasspath(FatJarPackageWizardPage.java:754) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizardPage.getSelectedElementsWithoutContainedChildren(FatJarPackageWizardPage.java:1024) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizardPage.getSelectedElementsWithoutContainedChildren(FatJarPackageWizardPage.java:695) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizard.performFinish(FatJarPackageWizard.java:206) - at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:790) - at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:423) - at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:618) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:249) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.jface.window.Window.runEventLoop(Window.java:818) - at org.eclipse.jface.window.Window.open(Window.java:794) - at org.eclipse.ui.internal.handlers.WizardHandler$Export.executeHandler(WizardHandler.java:106) - at org.eclipse.ui.internal.handlers.WizardHandler.execute(WizardHandler.java:290) - at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:295) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor54.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.ui.internal.handlers.LegacyHandlerService.executeCommand(LegacyHandlerService.java:353) - at org.eclipse.ui.internal.actions.CommandAction.runWithEvent(CommandAction.java:155) - at org.eclipse.ui.internal.actions.CommandAction.run(CommandAction.java:165) - at org.eclipse.ui.actions.ExportResourcesAction.run(ExportResourcesAction.java:119) - at org.eclipse.ui.actions.BaseSelectionListenerAction.runWithEvent(BaseSelectionListenerAction.java:167) - at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565) - at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:397) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 1 org.eclipse.jdt.launching 4 107 2017-06-03 22:39:38.741 -!MESSAGE Launch configuration Testing references non-existing project testing. - -!ENTRY org.eclipse.jdt.ui 4 10001 2017-06-03 22:40:00.756 -!MESSAGE Internal Error -!STACK 1 -org.eclipse.core.runtime.CoreException: Launch configuration Testing references non-existing project testing. - at org.eclipse.jdt.launching.JavaRuntime.abort(JavaRuntime.java:1408) - at org.eclipse.jdt.launching.JavaRuntime.getJavaProject(JavaRuntime.java:1283) - at org.eclipse.jdt.launching.StandardClasspathProvider.computeUnresolvedClasspath(StandardClasspathProvider.java:40) - at org.eclipse.jdt.launching.JavaRuntime.computeUnresolvedRuntimeClasspath(JavaRuntime.java:1246) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizardPage.getClasspath(FatJarPackageWizardPage.java:754) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizardPage.getSelectedElementsWithoutContainedChildren(FatJarPackageWizardPage.java:1024) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizardPage.getSelectedElementsWithoutContainedChildren(FatJarPackageWizardPage.java:695) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizard.performFinish(FatJarPackageWizard.java:206) - at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:790) - at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:423) - at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:618) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:249) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.jface.window.Window.runEventLoop(Window.java:818) - at org.eclipse.jface.window.Window.open(Window.java:794) - at org.eclipse.ui.internal.handlers.WizardHandler$Export.executeHandler(WizardHandler.java:106) - at org.eclipse.ui.internal.handlers.WizardHandler.execute(WizardHandler.java:290) - at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:295) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor54.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.ui.internal.handlers.LegacyHandlerService.executeCommand(LegacyHandlerService.java:353) - at org.eclipse.ui.internal.actions.CommandAction.runWithEvent(CommandAction.java:155) - at org.eclipse.ui.internal.actions.CommandAction.run(CommandAction.java:165) - at org.eclipse.ui.actions.ExportResourcesAction.run(ExportResourcesAction.java:119) - at org.eclipse.ui.actions.BaseSelectionListenerAction.runWithEvent(BaseSelectionListenerAction.java:167) - at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565) - at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:397) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 1 org.eclipse.jdt.launching 4 107 2017-06-03 22:40:00.758 -!MESSAGE Launch configuration Testing references non-existing project testing. - -!ENTRY org.eclipse.jdt.ui 4 10001 2017-06-03 22:40:52.792 -!MESSAGE Internal Error -!STACK 1 -org.eclipse.core.runtime.CoreException: Launch configuration Testing references non-existing project testing. - at org.eclipse.jdt.launching.JavaRuntime.abort(JavaRuntime.java:1408) - at org.eclipse.jdt.launching.JavaRuntime.getJavaProject(JavaRuntime.java:1283) - at org.eclipse.jdt.launching.StandardClasspathProvider.computeUnresolvedClasspath(StandardClasspathProvider.java:40) - at org.eclipse.jdt.launching.JavaRuntime.computeUnresolvedRuntimeClasspath(JavaRuntime.java:1246) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizardPage.getClasspath(FatJarPackageWizardPage.java:754) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizardPage.getSelectedElementsWithoutContainedChildren(FatJarPackageWizardPage.java:1024) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizardPage.getSelectedElementsWithoutContainedChildren(FatJarPackageWizardPage.java:695) - at org.eclipse.jdt.internal.ui.jarpackagerfat.FatJarPackageWizard.performFinish(FatJarPackageWizard.java:206) - at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:790) - at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:423) - at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:618) - at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:249) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.jface.window.Window.runEventLoop(Window.java:818) - at org.eclipse.jface.window.Window.open(Window.java:794) - at org.eclipse.ui.internal.handlers.WizardHandler$Export.executeHandler(WizardHandler.java:106) - at org.eclipse.ui.internal.handlers.WizardHandler.execute(WizardHandler.java:290) - at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:295) - at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) - at sun.reflect.GeneratedMethodAccessor54.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55) - at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:282) - at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:264) - at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) - at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) - at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494) - at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:488) - at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) - at org.eclipse.ui.internal.handlers.LegacyHandlerService.executeCommand(LegacyHandlerService.java:353) - at org.eclipse.ui.internal.actions.CommandAction.runWithEvent(CommandAction.java:155) - at org.eclipse.ui.internal.actions.CommandAction.run(CommandAction.java:165) - at org.eclipse.ui.actions.ExportResourcesAction.run(ExportResourcesAction.java:119) - at org.eclipse.ui.actions.BaseSelectionListenerAction.runWithEvent(BaseSelectionListenerAction.java:167) - at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565) - at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:397) - at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) - at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418) - at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079) - at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236) - at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022) - at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150) - at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693) - at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336) - at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610) - at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148) - at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138) - at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) - at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388) - at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673) - at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610) - at org.eclipse.equinox.launcher.Main.run(Main.java:1519) -!SUBENTRY 1 org.eclipse.jdt.launching 4 107 2017-06-03 22:40:52.795 -!MESSAGE Launch configuration Testing references non-existing project testing. -!SESSION 2017-06-04 09:53:21.942 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.jdt.core 4 0 2017-06-04 09:53:30.601 -!MESSAGE Invalid ZIP archive: C:\Users\Alvaro\Desktop\UnitParser.jar - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-04 09:53:30.695 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-04 12:02:03.984 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-04 12:02:09.630 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-04 12:05:41.196 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-04 12:05:47.441 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-04 13:01:33.879 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-04 13:01:40.092 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-04 15:32:05.518 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.core.resources 2 10035 2017-06-04 15:32:06.859 -!MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes. - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-04 15:32:11.782 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-04 16:50:50.233 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-04 16:50:56.586 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-05 21:53:04.438 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-05 21:53:11.429 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-05 21:54:44.287 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-05 21:54:51.268 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.jdt.debug 4 125 2017-06-05 22:23:58.008 -!MESSAGE Internal error logged from JDI Debug: -!STACK 0 -com.sun.jdi.VMOutOfMemoryException - at org.eclipse.jdi.internal.MirrorImpl.defaultReplyErrorHandler(MirrorImpl.java:285) - at org.eclipse.jdi.internal.ThreadReferenceImpl.threadGroup(ThreadReferenceImpl.java:618) - at org.eclipse.jdt.internal.debug.core.model.JDIThread.getUnderlyingThreadGroup(JDIThread.java:2229) - at org.eclipse.jdt.internal.debug.core.model.JDIThread.determineIfSystemThread(JDIThread.java:490) - at org.eclipse.jdt.internal.debug.core.model.JDIThread.initialize(JDIThread.java:287) - at org.eclipse.jdt.internal.debug.core.model.JDIThread.(JDIThread.java:267) - at org.eclipse.jdt.internal.debug.core.model.JDIDebugTarget.newThread(JDIDebugTarget.java:652) - at org.eclipse.jdt.internal.debug.core.model.JDIDebugTarget.createThread(JDIDebugTarget.java:628) - at org.eclipse.jdt.internal.debug.core.model.JDIDebugTarget$ThreadStartHandler.handleEvent(JDIDebugTarget.java:2326) - at org.eclipse.jdt.internal.debug.core.EventDispatcher.dispatch(EventDispatcher.java:152) - at org.eclipse.jdt.internal.debug.core.EventDispatcher.access$0(EventDispatcher.java:100) - at org.eclipse.jdt.internal.debug.core.EventDispatcher$1.run(EventDispatcher.java:250) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) -!SESSION 2017-06-06 09:57:25.881 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-06 09:57:33.058 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.recommenders.rcp 4 18 2017-06-06 11:40:34.148 -!MESSAGE Failed to resolve selection in ‘=UnitParser/src_Internal Git > Confirmations and Warnings preference page. -!SESSION 2017-06-06 15:00:48.491 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-06 15:00:55.162 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-06 15:53:18.572 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-06 15:53:24.575 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. - -!ENTRY org.eclipse.jdt.debug 4 125 2017-06-06 16:38:13.777 -!MESSAGE Internal error logged from JDI Debug: -!STACK 0 -com.sun.jdi.VMOutOfMemoryException - at org.eclipse.jdi.internal.MirrorImpl.defaultReplyErrorHandler(MirrorImpl.java:285) - at org.eclipse.jdi.internal.ThreadReferenceImpl.threadGroup(ThreadReferenceImpl.java:618) - at org.eclipse.jdt.internal.debug.core.model.JDIThread.getUnderlyingThreadGroup(JDIThread.java:2229) - at org.eclipse.jdt.internal.debug.core.model.JDIThread.determineIfSystemThread(JDIThread.java:490) - at org.eclipse.jdt.internal.debug.core.model.JDIThread.initialize(JDIThread.java:287) - at org.eclipse.jdt.internal.debug.core.model.JDIThread.(JDIThread.java:267) - at org.eclipse.jdt.internal.debug.core.model.JDIDebugTarget.newThread(JDIDebugTarget.java:652) - at org.eclipse.jdt.internal.debug.core.model.JDIDebugTarget.createThread(JDIDebugTarget.java:628) - at org.eclipse.jdt.internal.debug.core.model.JDIDebugTarget$ThreadStartHandler.handleEvent(JDIDebugTarget.java:2326) - at org.eclipse.jdt.internal.debug.core.EventDispatcher.dispatch(EventDispatcher.java:152) - at org.eclipse.jdt.internal.debug.core.EventDispatcher.access$0(EventDispatcher.java:100) - at org.eclipse.jdt.internal.debug.core.EventDispatcher$1.run(EventDispatcher.java:250) - at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) -!SESSION 2017-06-07 20:24:13.984 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.jdt.core 4 0 2017-06-07 20:24:22.456 -!MESSAGE Invalid ZIP archive: C:\Users\Alvaro\Desktop\UnitParser.jar - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-07 20:24:24.203 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-08 10:53:43.233 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-08 10:53:52.875 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-08 11:54:05.037 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-08 11:54:10.997 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-08 13:43:35.283 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-08 13:43:41.258 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-08 15:42:37.044 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-08 15:42:43.909 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-08 16:30:06.330 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-08 16:30:12.200 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-08 16:47:33.302 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-08 16:47:39.293 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-08 18:29:32.404 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-08 18:29:38.645 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-08 18:54:55.376 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-08 18:55:00.945 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-08 20:25:11.435 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-08 20:25:17.286 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-09 09:29:50.638 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-09 09:30:16.173 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-09 10:46:04.212 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.core.resources 2 10035 2017-06-09 10:46:05.585 -!MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes. - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-09 10:46:10.563 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-09 11:40:49.639 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-09 11:40:55.709 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-09 11:43:18.799 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-09 11:43:24.853 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-09 11:49:22.481 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-09 11:49:28.582 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. -!SESSION 2017-06-12 12:10:25.597 ----------------------------------------------- -eclipse.buildId=4.6.3.M20170301-0400 -java.version=1.8.0_131 -java.vendor=Oracle Corporation -BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=es_ES -Framework arguments: -product org.eclipse.epp.package.java.product -Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product - -!ENTRY org.eclipse.egit.ui 2 0 2017-06-12 12:10:31.698 -!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git -user global configuration and to define the default location to store repositories: 'C:\Users\Alvaro'. If this is -not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and -EGit might behave differently since they see different configuration options. -This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. diff --git a/all_code/.metadata/.mylyn/.taskListIndex/segments.gen b/all_code/.metadata/.mylyn/.taskListIndex/segments.gen deleted file mode 100644 index 63a7ec9..0000000 Binary files a/all_code/.metadata/.mylyn/.taskListIndex/segments.gen and /dev/null differ diff --git a/all_code/.metadata/.mylyn/.taskListIndex/segments_1 b/all_code/.metadata/.mylyn/.taskListIndex/segments_1 deleted file mode 100644 index c8a4717..0000000 Binary files a/all_code/.metadata/.mylyn/.taskListIndex/segments_1 and /dev/null differ diff --git a/all_code/.metadata/.mylyn/.tasks.xml.zip b/all_code/.metadata/.mylyn/.tasks.xml.zip deleted file mode 100644 index 1c9383b..0000000 Binary files a/all_code/.metadata/.mylyn/.tasks.xml.zip and /dev/null differ diff --git a/all_code/.metadata/.mylyn/repositories.xml.zip b/all_code/.metadata/.mylyn/repositories.xml.zip deleted file mode 100644 index 8d1fc52..0000000 Binary files a/all_code/.metadata/.mylyn/repositories.xml.zip and /dev/null differ diff --git a/all_code/.metadata/.mylyn/tasks.xml.zip b/all_code/.metadata/.mylyn/tasks.xml.zip deleted file mode 100644 index 63ad7dc..0000000 Binary files a/all_code/.metadata/.mylyn/tasks.xml.zip and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1/20810f3b614c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1/20810f3b614c0017146ede6da4ae5d42 deleted file mode 100644 index 5520a55..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1/20810f3b614c0017146ede6da4ae5d42 +++ /dev/null @@ -1,283 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class HCPrefixes -{ - /** - Relates the SI prefixes (SIPrefixes enum) with their values (constants in the SIPrefixValues class). - **/ - public static HashMap AllSIPrefixes; - - //Relates the SI prefix strings (SIPrefixSymbols enum) with their values (constants in the SIPrefixValues class). - public static HashMap AllSIPrefixSymbols; - - //Relates the binary prefixes (BinaryPrefixes enum) with their values (constants in the BinaryPrefixValues class). - public static HashMap AllBinaryPrefixes; - - //Relates the binary prefix strings (BinaryPrefixSymbols enum) with their values (constants in the BinaryPrefixValues class). - public static HashMap AllBinaryPrefixSymbols; - - //Contains all the units outside the SI-prefix-supporting systems (i.e., UnitSystems.SI & UnitSystems.CGS) - //which do support SI prefixes by default. - public static ArrayList AllOtherSIPrefixUnits; - - //By default, global prefixes aren't used with compounds to avoid misunderstandings. For example: 1000 m^2 converted - //into k m^2 confused as km2. This collection includes all the compounds which might use prefixes. - public static ArrayList AllCompoundsUsingPrefixes; - - //Includes all the unit types which support binary prefixes by default. - public static ArrayList AllBinaryPrefixTypes; - - //All the collections below this line are secondary/used for very specific purposes. That's why they - //are only populated when being used for the first time. - - //The full names of all the SI/binary prefixes. - public static HashMap AllSIPrefixNames, AllBinaryPrefixNames; - - //Various collections used in prefix-related calculations. - public static ArrayList BigSIPrefixValues, SmallSIPrefixValues, BigBinaryPrefixValues, SmallBinaryPrefixValues; - - public static String Start() - { - AllBinaryPrefixTypes = new ArrayList() - {{ - add(UnitTypes.Information); add(UnitTypes.BitRate); add(UnitTypes.SymbolRate); - }}; - - AllCompoundsUsingPrefixes = new ArrayList() - {{ - //--- Area - add(Units.Rood); add(Units.Acre); add(Units.SurveyAcre); - - //--- Volume - add(Units.FluidOunce); add(Units.ImperialFluidOunce); add(Units.USCSFluidOunce); add(Units.Gill); - add(Units.ImperialGill); add(Units.USCSGill); add(Units.Pint); add(Units.ImperialPint); add(Units.LiquidPint); - add(Units.DryPint); add(Units.Quart); add(Units.ImperialQuart); add(Units.LiquidQuart); add(Units.DryQuart); - add(Units.Gallon); add(Units.LiquidGallon); add(Units.DryGallon); - - //--- Velocity - add(Units.Knot); - - //--- Acceleration - add(Units.Gal); - - //--- Force - add(Units.Newton); add(Units.Dyne); add(Units.PoundForce); add(Units.Poundal); add(Units.OunceForce); - - //--- Energy - add(Units.Joule); add(Units.Erg); add(Units.WattHour); add(Units.Calorie); add(Units.ThermochemicalCalorie); - add(Units.FoodCalorie); add(Units.BritishThermalUnit); add(Units.ThermochemicalBritishThermalUnit); - add(Units.Therm); add(Units.UKTherm); add(Units.USTherm); - - //--- Power - add(Units.Watt); add(Units.Horsepower); add(Units.MetricHorsepower); add(Units.ElectricHorsepower); - add(Units.BoilerHorsepower); add(Units.TonOfRefrigeration); - - //--- Pressure - add(Units.Pascal); add(Units.Barye); add(Units.Atmosphere); add(Units.TechnicalAtmosphere); add(Units.Bar); - add(Units.Torr); - - //--- Frequency - add(Units.Hertz); - - //--- Electric Charge - add(Units.AmpereHour); - - //--- Electric Current - add(Units.Ampere); add(Units.Statampere); add(Units.Abampere); add(Units.Biot); - - //--- Electric Voltage - add(Units.Volt); add(Units.Statvolt); add(Units.Abvolt); - - //--- Electric Resitance - add(Units.Ohm); add(Units.Statohm); add(Units.Abohm); - - //--- Electric Conductance - add(Units.Siemens); add(Units.Mho); add(Units.Gemmho); add(Units.Statsiemens); add(Units.Statmho); - add(Units.Absiemens); add(Units.Abmho); - - //--- Electric Capacitance - add(Units.Farad); add(Units.Statfarad); add(Units.Abfarad); - - //--- Electric Inductance - add(Units.Henry); add(Units.Stathenry); add(Units.Abhenry); - - //--- Electric Dipole Moment - add(Units.Debye); - - //--- Wavenumber - add(Units.Kayser); - - //--- Viscosity - add(Units.Poise); - - //--- Kinematic Viscosity - add(Units.Stokes); - - //--- Solid Angle - add(Units.Steradian); - - //--- Luminous Flux - add(Units.Lumen); - - //--- Luminous Energy - add(Units.Talbot); - - //--- Luminance - add(Units.Stilb); add(Units.Nit); add(Units.Lambert); add(Units.FootLambert); - - //--- Illuminance - add(Units.Lux); add(Units.Phot); add(Units.FootCandle); - - //--- Magnetic Flux - add(Units.Weber); add(Units.Maxwell); - - //--- Magnetic Field H - add(Units.Oersted); - - //--- Magnetic Field B - add(Units.Tesla); add(Units.Gauss); - - //--- Absorbed Dose - add(Units.Gray); add(Units.Rad); - - //--- Equivalent Dose - add(Units.Sievert); add(Units.REM); - - //--- Exposure - add(Units.Roentgen); - - //--- Catalytic Activity - add(Units.Katal); - - //--- Bit Rate - add(Units.BitPerSecond); - }}; - - AllOtherSIPrefixUnits = new ArrayList() - {{ - //--- Length - add(Units.Parsec); - - //--- Mass - add(Units.MetricTon); add(Units.Dalton); add(Units.UnifiedAtomicMassUnit); - - //--- Area - add(Units.Are); add(Units.Barn); - - //--- Volume - add(Units.Litre); - - //--- Information - add(Units.Bit); add(Units.Byte); add(Units.Nibble); add(Units.Quartet); add(Units.Octet); - - //--- Energy - add(Units.Electronvolt); add(Units.WattHour); add(Units.Calorie); add(Units.ThermochemicalCalorie); - - //--- Pressure - add(Units.Bar); add(Units.Torr); - - //--- Electric Charge - add(Units.AmpereHour); - - //--- Logarithmic - add(Units.Bel); add(Units.Neper); - - //--- Radioactivity - add(Units.Curie); - - //--- Bit Rate - add(Units.BitPerSecond); - - //--- Symbol Rate - add(Units.Baud); - }}; - - AllBinaryPrefixSymbols = new HashMap() - { - { - put(BinaryPrefixSymbols.Kibi, BinaryPrefixValues.Kibi); - put(BinaryPrefixSymbols.Mebi, BinaryPrefixValues.Mebi); - put(BinaryPrefixSymbols.Gibi, BinaryPrefixValues.Gibi); - put(BinaryPrefixSymbols.Tebi, BinaryPrefixValues.Tebi); - put(BinaryPrefixSymbols.Pebi, BinaryPrefixValues.Pebi); - put(BinaryPrefixSymbols.Exbi, BinaryPrefixValues.Exbi); - put(BinaryPrefixSymbols.Zebi, BinaryPrefixValues.Zebi); - put(BinaryPrefixSymbols.Yobi, BinaryPrefixValues.Yobi); - } - }; - - AllBinaryPrefixes = new HashMap() - { - { - put(BinaryPrefixes.Kibi, BinaryPrefixValues.Kibi); - put(BinaryPrefixes.Mebi, BinaryPrefixValues.Mebi); - put(BinaryPrefixes.Gibi, BinaryPrefixValues.Gibi); - put(BinaryPrefixes.Tebi, BinaryPrefixValues.Tebi); - put(BinaryPrefixes.Pebi, BinaryPrefixValues.Pebi); - put(BinaryPrefixes.Exbi, BinaryPrefixValues.Exbi); - put(BinaryPrefixes.Zebi, BinaryPrefixValues.Zebi); - put(BinaryPrefixes.Yobi, BinaryPrefixValues.Yobi); - } - }; - - AllSIPrefixSymbols = new HashMap() - { - { - put(SIPrefixSymbols.Yotta, SIPrefixValues.Yotta); - put(SIPrefixSymbols.Zetta, SIPrefixValues.Zetta); - put(SIPrefixSymbols.Exa, SIPrefixValues.Exa); - put(SIPrefixSymbols.Peta, SIPrefixValues.Peta); - put(SIPrefixSymbols.Tera, SIPrefixValues.Tera); - put(SIPrefixSymbols.Giga, SIPrefixValues.Giga); - put(SIPrefixSymbols.Mega, SIPrefixValues.Mega); - put(SIPrefixSymbols.Kilo, SIPrefixValues.Kilo); - put(SIPrefixSymbols.Hecto, SIPrefixValues.Hecto); - put(SIPrefixSymbols.Deca, SIPrefixValues.Deca); - put(SIPrefixSymbols.Deci, SIPrefixValues.Deci); - put(SIPrefixSymbols.Centi, SIPrefixValues.Centi); - put(SIPrefixSymbols.Milli, SIPrefixValues.Milli); - put(SIPrefixSymbols.Micro, SIPrefixValues.Micro); - put(SIPrefixSymbols.Nano, SIPrefixValues.Nano); - put(SIPrefixSymbols.Pico, SIPrefixValues.Pico); - put(SIPrefixSymbols.Femto, SIPrefixValues.Femto); - put(SIPrefixSymbols.Atto, SIPrefixValues.Atto); - put(SIPrefixSymbols.Zepto, SIPrefixValues.Zepto); - put(SIPrefixSymbols.Yocto, SIPrefixValues.Yocto); - } - }; - - AllSIPrefixes = new HashMap() - { - { - put(SIPrefixes.Yotta, SIPrefixValues.Yotta); - put(SIPrefixes.Zetta, SIPrefixValues.Zetta); - put(SIPrefixes.Exa, SIPrefixValues.Exa); - put(SIPrefixes.Peta, SIPrefixValues.Peta); - put(SIPrefixes.Tera, SIPrefixValues.Tera); - put(SIPrefixes.Giga, SIPrefixValues.Giga); - put(SIPrefixes.Mega, SIPrefixValues.Mega); - put(SIPrefixes.Kilo, SIPrefixValues.Kilo); - put(SIPrefixes.Hecto, SIPrefixValues.Hecto); - put(SIPrefixes.Deca, SIPrefixValues.Deca); - put(SIPrefixes.Deci, SIPrefixValues.Deci); - put(SIPrefixes.Centi, SIPrefixValues.Centi); - put(SIPrefixes.Milli, SIPrefixValues.Milli); - put(SIPrefixes.Micro, SIPrefixValues.Micro); - put(SIPrefixes.Nano, SIPrefixValues.Nano); - put(SIPrefixes.Pico, SIPrefixValues.Pico); - put(SIPrefixes.Femto, SIPrefixValues.Femto); - put(SIPrefixes.Atto, SIPrefixValues.Atto); - put(SIPrefixes.Zepto, SIPrefixValues.Zepto); - put(SIPrefixes.Yocto, SIPrefixValues.Yocto); - } - }; - - return ""; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1/80f17d12b14a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1/80f17d12b14a00171059ebc16969059f deleted file mode 100644 index 18b4ea2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1/80f17d12b14a00171059ebc16969059f +++ /dev/null @@ -1,1056 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - - System.out.println("asfdasf"); - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1/d0feb29bb34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1/d0feb29bb34a00171059ebc16969059f deleted file mode 100644 index 5355d2b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1/d0feb29bb34a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - System.out.println(outInfo.Value); - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/10/303b62bc6d4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/10/303b62bc6d4c00171838d4a3813404a0 deleted file mode 100644 index b19f52c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/10/303b62bc6d4c00171838d4a3813404a0 +++ /dev/null @@ -1,254 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - if (input == null) return defaultVal; - - ArrayList tempVar = - ( - filter == null ? input : - Where(input, filter) - ); - if (tempVar == null) return defaultVal; - - return GetFirst(input2, filter, defaultVal); ; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/10/30f6b588b24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/10/30f6b588b24a00171059ebc16969059f deleted file mode 100644 index e4c392d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/10/30f6b588b24a00171059ebc16969059f +++ /dev/null @@ -1,566 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - System.out.println(outInfo.Value); - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/10/c094c7c42c4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/10/c094c7c42c4a001712d4a4f7b050cac8 deleted file mode 100644 index f42a0ef..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/10/c094c7c42c4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); -System.out.println(outUnit); - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/11/c04d37739b4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/11/c04d37739b4a00171930ee4d171ed0de deleted file mode 100644 index 8e64f5a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/11/c04d37739b4a00171930ee4d171ed0de +++ /dev/null @@ -1,1858 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - System.out.println(targetExponent); - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - //System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/a0231f2b5d4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/a0231f2b5d4c0017146ede6da4ae5d42 deleted file mode 100644 index 43b56a3..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/a0231f2b5d4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,162 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return (first.Error.equals(second.Error)); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type != ErrorTypes.None || secondInfo.Error.Type != ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling.equals(second.ExceptionHandling) && - first.Type.equals(second.Type) - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/c0ca15bfb24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/c0ca15bfb24a00171059ebc16969059f deleted file mode 100644 index 02588a9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/c0ca15bfb24a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - System.out.println("here"); - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/c0d9b3cd294a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/c0d9b3cd294a001712d4a4f7b050cac8 deleted file mode 100644 index f1ca901..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/c0d9b3cd294a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - System.out.println(parseInfo.UnitInfo.Parts.get(0).Unit); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/c0eb94285c4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/c0eb94285c4c0017146ede6da4ae5d42 deleted file mode 100644 index 9145f7e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/12/c0eb94285c4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1200 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - ///Determines whether the current UnitP instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this UnitP instance. - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/10e7c0a9bf4a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/10e7c0a9bf4a00171634abff01ee97d5 deleted file mode 100644 index a79bef9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/10e7c0a9bf4a00171634abff01ee97d5 +++ /dev/null @@ -1,13 +0,0 @@ -package test0; - -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft")); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/209b28625c4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/209b28625c4c0017146ede6da4ae5d42 deleted file mode 100644 index 4072da0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/209b28625c4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,163 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - System.out.println(UnitPNonUnitInfoAreEqual(first, second)); - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return (first.Error.equals(second.Error)); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type != ErrorTypes.None || secondInfo.Error.Type != ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling.equals(second.ExceptionHandling) && - first.Type.equals(second.Type) - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/20c227c76c4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/20c227c76c4c00171838d4a3813404a0 deleted file mode 100644 index dc45ec9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/20c227c76c4c00171838d4a3813404a0 +++ /dev/null @@ -1,248 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - return GetFirst(input2, filter, defaultVal); ; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = - ( - filter == null ? input : - WhereDict(input, filter) - ); - if (filter != null) - { - tempVar = WhereDict(input, filter); - } - if (tempVar == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(tempVar), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/30a16384614c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/30a16384614c0017146ede6da4ae5d42 deleted file mode 100644 index 3e7e313..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/30a16384614c0017146ede6da4ae5d42 +++ /dev/null @@ -1,24 +0,0 @@ -package test0; - -import java.util.ArrayList; -import java.util.Collections; - -import UnitParser.*; - -public class Main -{ - public static void main(String[] args) throws Exception - { - ArrayList tests = new ArrayList(); - tests.add(new Prefix(2555.0)); - tests.add(new Prefix(1000.0)); - tests.add(new Prefix(500000)); - - Collections.sort(tests); - - for (Prefix item: tests) - { - System.out.println(item.Factor); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/b1e1bf967d4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/b1e1bf967d4c00171945f16efe0d9b5d deleted file mode 100644 index eb1aa35..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/13/b1e1bf967d4c00171945f16efe0d9b5d +++ /dev/null @@ -1,227 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.HashMap; - - -//Class storing all the unit-related information. -//It includes the main numeric variables (Value, Prefix.Factor & BaseTenExponent) and, consequently, -//is also the main class when dealing with managed operations (i.e., error-free-ly dealing with numbers of any size). -//This class is part of the internal/private code of the original C# version and users aren't expected to rely on it at all. -public class UnitInfo -{ - public Double Value; - public Units Unit; - public UnitSystems System; - public UnitTypes Type; - public Prefix Prefix; - public ArrayList Parts; - public ErrorInfo Error; - public String TempString; - public Integer BaseTenExponent; - //Collection storing the positions of the unit parts as input by the user. - public HashMap InitialPositions; - - public UnitInfo() throws Exception { this(0.0); } - - public UnitInfo(Units unit) throws Exception { this(unit, 1.0); } - - public UnitInfo(Units unit, Double prefixFactor) throws Exception { this(0.0, unit, new Prefix(prefixFactor)); } - - public UnitInfo(Double value, Units unit, Prefix prefix, boolean getParts) throws Exception - { - this(value, unit, prefix, getParts, ExceptionHandlingTypes.NeverTriggerException); - } - - public UnitInfo(Double value, Units unit, Prefix prefix) throws Exception - { - this(value, unit, prefix, true, ExceptionHandlingTypes.NeverTriggerException); - } - - public UnitInfo - ( - Double value, Units unit, Prefix prefix, boolean getParts, - ExceptionHandlingTypes exceptionHandling - ) - throws Exception - { - PopulateVariables - ( - value, unit, prefix, (getParts ? null : new ArrayList()), - new HashMap(), 0, UnitTypes.None, UnitSystems.None, - new ErrorInfo(ErrorTypes.None, exceptionHandling) - ); - } - - public UnitInfo(UnitInfo unitInfo) throws Exception - { - this(unitInfo, ErrorTypes.None); - } - - public UnitInfo(UnitInfo unitInfo, ErrorTypes error) throws Exception - { - if (unitInfo == null) unitInfo = new UnitInfo(); - - PopulateVariables - ( - unitInfo.Value, unitInfo.Unit, unitInfo.Prefix, - unitInfo.Parts, MethodsCommon.GetInitialPositions(unitInfo.Parts), - unitInfo.BaseTenExponent, unitInfo.Type, unitInfo.System, - (error != ErrorTypes.None ? new ErrorInfo(error) : unitInfo.Error) - ); - } - - public UnitInfo(Double value, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) throws Exception - { - UnitInfo unitInfo = new UnitInfo(value); - - PopulateVariables - ( - unitInfo.Value, unitInfo.Unit, new Prefix(unitInfo.Prefix.Factor, prefixUsage), - unitInfo.Parts, MethodsCommon.GetInitialPositions(unitInfo.Parts), - unitInfo.BaseTenExponent, unitInfo.Type, unitInfo.System, - new ErrorInfo(ErrorTypes.None, exceptionHandling) - ); - } - - public UnitInfo(UnitP unitP) throws Exception - { - if (unitP == null) - { - Prefix = new Prefix(); - Parts = new ArrayList(); - Error = new ErrorInfo(); - return; - } - - ArrayList unitParts = new ArrayList(); - if (unitP.UnitParts != null && unitP.UnitParts.size() > 0) - { - unitParts = new ArrayList(unitP.UnitParts); - } - - PopulateVariables - ( - unitP.Value, unitP.Unit, unitP.UnitPrefix, unitParts, - MethodsCommon.GetInitialPositions(unitParts), unitP.BaseTenExponent, - unitP.UnitType, unitP.UnitSystem, unitP.Error - ); - } - - public UnitInfo(Double value) throws Exception - { - this(value, 0); - } - - public UnitInfo(Double value, int baseTenExponent) throws Exception - { - PopulateVariables(value, Units.None, new Prefix(), null, null, baseTenExponent); - } - - void PopulateVariables - ( - Double value, Units unit, Prefix prefix, ArrayList parts, HashMap initialPositions - ) - throws Exception - { - PopulateVariables(value, unit, prefix, parts, initialPositions, 0); - } - - void PopulateVariables - ( - Double value, Units unit, Prefix prefix, ArrayList parts, HashMap initialPositions, - int baseTenExponent - ) - throws Exception - { - PopulateVariables(value, unit, prefix, parts, initialPositions, baseTenExponent, UnitTypes.None); - } - - void PopulateVariables - ( - Double value, Units unit, Prefix prefix, ArrayList parts, HashMap initialPositions, - int baseTenExponent, UnitTypes type - ) - throws Exception - { - PopulateVariables(value, unit, prefix, parts, initialPositions, baseTenExponent, type, UnitSystems.None); - } - - void PopulateVariables - ( - Double value, Units unit, Prefix prefix, ArrayList parts, - HashMap initialPositions, int baseTenExponent, - UnitTypes type, UnitSystems system - ) - throws Exception - { - PopulateVariables(value, unit, prefix, parts, initialPositions, baseTenExponent, type, system, null); - } - - void PopulateVariables - ( - Double value, Units unit, Prefix prefix, ArrayList parts, - HashMap initialPositions, int baseTenExponent, - UnitTypes type, UnitSystems system, ErrorInfo errorInfo - ) - throws Exception - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unit; - Prefix = new Prefix(prefix); - if (parts == null) - { - Parts = new ArrayList(); - UnitInfo tempInfo = MethodsCommon.GetUnitParts - ( - new UnitInfo(1.0, Unit, Prefix, false) - ); - - if (tempInfo.Value != 1 || tempInfo.BaseTenExponent != 0) - { - //While getting the parts, some automatic conversions might occur and - //the associated values have to be accounted for. - tempInfo = Managed.NormaliseUnitInfo(tempInfo); - BaseTenExponent += tempInfo.BaseTenExponent; - try - { - Value *= tempInfo.Value; - } - catch(Exception e) - { - try - { - //Very unlikely scenario, but possible. - Value /= 10; - BaseTenExponent += 1; - Value *= tempInfo.Value; - } - catch(Exception e2) - { - //The only way to reach this point is in case that the maximum - //BaseTenExponent (i.e., int.MaxValue) has been reached. There - //is only one possible output for such an scenario: an error. - errorInfo = new ErrorInfo(ErrorTypes.NumericError); - } - } - } - Parts = tempInfo.Parts; - InitialPositions = MethodsCommon.GetInitialPositions(Parts); - } - else - { - InitialPositions = new HashMap(initialPositions); - Parts = new ArrayList(parts); - } - System = system; - Type = type; - TempString = ""; - Error = new ErrorInfo(errorInfo); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/50240e20284c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/50240e20284c00171ae7fcf2c321c986 deleted file mode 100644 index 7b7a9cd..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/50240e20284c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - System.out.println(tempInfo.Value + " " + tempInfo.BaseTenExponent); - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/703b448db34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/703b448db34a00171059ebc16969059f deleted file mode 100644 index b42018d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/703b448db34a00171059ebc16969059f +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - System.out.println(outInfo.Value + " " + outInfo.BaseTenExponent + " -- " + secondInfo.Value + " " + secondInfo.BaseTenExponent); - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/c07ae0f6f34c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/c07ae0f6f34c00171048b3f61ecb42d3 deleted file mode 100644 index c86db85..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/c07ae0f6f34c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1224 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return Array list including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return Array list including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return Array list including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return Array list including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return Array list including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return Array list including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList variable including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/c0e8ea302b4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/c0e8ea302b4a001712d4a4f7b050cac8 deleted file mode 100644 index 1bbb4c6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/c0e8ea302b4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1165 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - System.out.println("asfasf"); - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/e0edc2c9944a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/e0edc2c9944a00171930ee4d171ed0de deleted file mode 100644 index d0e5211..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/14/e0edc2c9944a00171930ee4d171ed0de +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/16/10a9ac30614c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/16/10a9ac30614c0017146ede6da4ae5d42 deleted file mode 100644 index 85e96cb..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/16/10a9ac30614c0017146ede6da4ae5d42 +++ /dev/null @@ -1,2563 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import InternalUnitParser.Classes.*; -import UnitParser.*; - -import java.util.HashMap; -import java.util.ArrayList; - - -@SuppressWarnings("serial") -public class HCCompounds -{ - /** - Contains the definitions of all the supported compounds, understood as units formed by other units - and/or variations (e.g., exponents different than 1) of them. - In order to be as efficient as possible, AllCompounds ignores the difference between dividable and - non-dividable units. For example: N is formed by kg*m/s2, exactly what this collection expects; on the - other hand, lbf isn't formed by the expected lb*ft/s2. In any case, note that this "faulty" format is - only used internally, never shown to the user. - NOTE: the order of the compounds within each type does matter. The first position is reserved for the main - fully-expanded version (e.g., mass*length/time2 for force). In the second position, the compound basic - units (e.g., force) are expected to have their 1-part version (e.g., 1 force part for force). - **/ - public static HashMap> AllCompounds; - /** - Contains all the named compounds defined by the basic units for the given type/system. - For example, Newton is formed by kg*m/s^2, the basic mass*length/time units in SI, and that's why it belongs here. - **/ - public static HashMap> AllBasicCompounds; - - //Roughly speaking, AllNonBasicCompounds is a container of somehow exceptional situations. - //Some of these units (e.g., centimetre) shouldn't be matched when looking for valid compounds. - public static ArrayList NonBasicCompoundsToSkip; - - //Contains the definition (i.e., UnitPart[] containing their defining units) of all the supported named - //compounds except the ones defined by the corresponding basic units (included in AllBasicCompounds). - public static HashMap> AllNonBasicCompounds; - - //Classifies all the basic units on account of their types and systems. - //Note that these units don't meet the most intuitive interpretation of the basic unit idea. - //That is, they aren't just the most basic constituent of compounds (i.e., impossible to be - //further divided), but also compounds. The reason for this a-priori abnormal configuration - //is that they aren't just used to model SI/CGS compounds, but also Imperial/USCS ones. - //For example: the SI force unit (N) can be defined on account of properly-speaking basic units, - //but the Imperial/USCS version (lbf) cannot. - public static HashMap> AllBasicUnits; - - public static String Start() - { - AllCompounds = new HashMap>() - { - { - { - put - ( - UnitTypes.Area, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Length, 2)); }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Area)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Volume, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Length, 3)); }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Volume)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Velocity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Acceleration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Force, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Force)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Energy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Energy)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Power, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Power)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Pressure, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -1)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Frequency, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Time, -1)); }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricCharge, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricVoltage, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricResistance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricResistivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricConductance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricConductivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricCapacitance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 4)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricInductance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricDipoleMoment, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time, 1)); - add(new CompoundPart(UnitTypes.Length, 1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Wavenumber, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Length, -1)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Viscosity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -1)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.KinematicViscosity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Momentum, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AngularVelocity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Angle)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AngularAcceleration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Angle)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AngularMomentum, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MomentOfInertia, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SolidAngle, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Angle, 2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.LuminousFlux, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.SolidAngle)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.LuminousEnergy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.SolidAngle)); - add(new CompoundPart(UnitTypes.Time)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Luminance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Illuminance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.SolidAngle)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MagneticFlux, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MagneticFieldB, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MagneticFieldH, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Length, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AbsorbedDose, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AbsorbedDoseRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.EquivalentDose, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Exposure, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Mass, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.CatalyticActivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.CatalyticActivityConcentration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Time, -1)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Jerk, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MassFlowRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Density, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AreaDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.EnergyDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -1)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SpecificVolume, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.Mass, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.VolumetricFlowRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SurfaceTension, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SpecificWeight, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalConductivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalConductance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalResistivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Temperature)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalResistance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Temperature)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.HeatTransferCoefficient, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.HeatFluxDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Entropy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricFieldStrength, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.LinearElectricChargeDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Length, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.CurrentDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectromagneticPermittivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 4)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectromagneticPermeability, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 1)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarEnergy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarEntropy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarVolume, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarMass, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarConcentration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolalConcentration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Mass, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.RadiantIntensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.SolidAngle, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Radiance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.SolidAngle, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.FuelEconomy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SoundExposure, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass, 2)); - add(new CompoundPart(UnitTypes.Length, -2)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SoundImpedance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -4)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.RotationalStiffness, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.Angle, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.BitRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Information)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - } - } - }; - - AllBasicCompounds = new HashMap>() - { - { - { - put - ( - UnitTypes.Area, new HashMap() - { - { - put(UnitSystems.SI, Units.SquareMetre); - put(UnitSystems.CGS, Units.SquareCentimetre); - put(UnitSystems.Imperial, Units.SquareFoot); - } - } - ); - put - ( - UnitTypes.Volume, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetre); - put(UnitSystems.CGS, Units.CubicCentimetre); - put(UnitSystems.Imperial, Units.CubicFoot); - } - } - ); - put - ( - UnitTypes.Velocity, new HashMap() - { - { - put(UnitSystems.SI, Units.MetrePerSecond); - put(UnitSystems.CGS, Units.CentimetrePerSecond); - put(UnitSystems.Imperial, Units.FootPerSecond); - } - } - ); - put - ( - UnitTypes.Acceleration, new HashMap() - { - { - put(UnitSystems.SI, Units.MetrePerSquareSecond); - put(UnitSystems.CGS, Units.Gal); - put(UnitSystems.Imperial, Units.FootPerSquareSecond); - } - } - ); - put - ( - UnitTypes.Force, new HashMap() - { - { - put(UnitSystems.SI, Units.Newton); - put(UnitSystems.CGS, Units.Dyne); - put(UnitSystems.Imperial, Units.Poundal); - } - } - ); - put - ( - UnitTypes.Energy, new HashMap() - { - { - put(UnitSystems.SI, Units.Joule); - put(UnitSystems.CGS, Units.Erg); - } - } - ); - put - ( - UnitTypes.Power, new HashMap() - { - { - put(UnitSystems.SI, Units.Watt); - put(UnitSystems.CGS, Units.ErgPerSecond); - } - } - ); - put - ( - UnitTypes.Pressure, new HashMap() - { - { - put(UnitSystems.SI, Units.Pascal); - put(UnitSystems.CGS, Units.Barye); - put(UnitSystems.Imperial, Units.PoundforcePerSquareFoot); - } - } - ); - put - ( - UnitTypes.Frequency, new HashMap() - { - { - put(UnitSystems.SI, Units.Hertz); - } - } - ); - put - ( - UnitTypes.ElectricCharge, new HashMap() - { - { - put(UnitSystems.SI, Units.Coulomb); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, new HashMap() - { - { - put(UnitSystems.SI, Units.Ampere); - } - } - ); - put - ( - UnitTypes.ElectricVoltage, new HashMap() - { - { - put(UnitSystems.SI, Units.Volt); - } - } - ); - put - ( - UnitTypes.ElectricResistance, new HashMap() - { - { - put(UnitSystems.SI, Units.Ohm); - } - } - ); - put - ( - UnitTypes.ElectricResistivity, new HashMap() - { - { - put(UnitSystems.SI, Units.OhmMetre); - } - } - ); - put - ( - UnitTypes.ElectricConductance, new HashMap() - { - { - put(UnitSystems.SI, Units.Siemens); - } - } - ); - put - ( - UnitTypes.ElectricConductivity, new HashMap() - { - { - put(UnitSystems.SI, Units.SiemensPerMetre); - } - } - ); - put - ( - UnitTypes.ElectricCapacitance, new HashMap() - { - { - put(UnitSystems.SI, Units.Farad); - } - } - ); - put - ( - UnitTypes.ElectricInductance, new HashMap() - { - { - put(UnitSystems.SI, Units.Henry); - } - } - ); - put - ( - UnitTypes.ElectricDipoleMoment, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombMetre); - } - } - ); - put - ( - UnitTypes.Wavenumber, new HashMap() - { - { - put(UnitSystems.SI, Units.ReciprocalMetre); - put(UnitSystems.CGS, Units.Kayser); - } - } - ); - put - ( - UnitTypes.Viscosity, new HashMap() - { - { - put(UnitSystems.SI, Units.PascalSecond); - put(UnitSystems.CGS, Units.Poise); - } - } - ); - put - ( - UnitTypes.KinematicViscosity, new HashMap() - { - { - put(UnitSystems.SI, Units.SquareMetrePerSecond); - put(UnitSystems.CGS, Units.Stokes); - } - } - ); - put - ( - UnitTypes.Momentum, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonSecond); - } - } - ); - put - ( - UnitTypes.AngularVelocity, new HashMap() - { - { - put(UnitSystems.SI, Units.RadianPerSecond); - } - } - ); - put - ( - UnitTypes.AngularAcceleration, new HashMap() - { - { - put(UnitSystems.SI, Units.RadianPerSquareSecond); - } - } - ); - put - ( - UnitTypes.AngularMomentum, new HashMap() - { - { - put(UnitSystems.SI, Units.JouleSecond); - } - } - ); - put - ( - UnitTypes.MomentOfInertia, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramSquareMetre); - } - } - ); - put - ( - UnitTypes.SolidAngle, new HashMap() - { - { - put(UnitSystems.SI, Units.Steradian); - } - } - ); - put - ( - UnitTypes.LuminousFlux, new HashMap() - { - { - put(UnitSystems.SI, Units.Lumen); - } - } - ); - put - ( - UnitTypes.LuminousEnergy, new HashMap() - { - { - put(UnitSystems.SI, Units.LumenSecond); - } - } - ); - put - ( - UnitTypes.Luminance, new HashMap() - { - { - put(UnitSystems.SI, Units.CandelaPerSquareMetre); - put(UnitSystems.CGS, Units.Stilb); - } - } - ); - put - ( - UnitTypes.Illuminance, new HashMap() - { - { - put(UnitSystems.SI, Units.Lux); - put(UnitSystems.CGS, Units.Phot); - put(UnitSystems.Imperial, Units.FootCandle); - } - } - ); - put - ( - UnitTypes.MagneticFlux, new HashMap() - { - { - put(UnitSystems.SI, Units.Weber); - } - } - ); - put - ( - UnitTypes.MagneticFieldB, new HashMap() - { - { - put(UnitSystems.SI, Units.Tesla); - } - } - ); - put - ( - UnitTypes.AbsorbedDose, new HashMap() - { - { - put(UnitSystems.SI, Units.Gray); - } - } - ); - put - ( - UnitTypes.AbsorbedDoseRate, new HashMap() - { - { - put(UnitSystems.SI, Units.GrayPerSecond); - } - } - ); - put - ( - UnitTypes.EquivalentDose, new HashMap() - { - { - put(UnitSystems.SI, Units.Sievert); - } - } - ); - put - ( - UnitTypes.Exposure, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerKilogram); - put(UnitSystems.CGS, Units.Roentgen); - } - } - ); - put - ( - UnitTypes.CatalyticActivity, new HashMap() - { - { - put(UnitSystems.SI, Units.Katal); - } - } - ); - put - ( - UnitTypes.CatalyticActivityConcentration, new HashMap() - { - { - put(UnitSystems.SI, Units.KatalPerCubicMetre); - } - } - ); - put - ( - UnitTypes.Jerk, new HashMap() - { - { - put(UnitSystems.SI, Units.MetrePerCubicSecond); - } - } - ); - put - ( - UnitTypes.MassFlowRate, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerSecond); - } - } - ); - put - ( - UnitTypes.Density, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerCubicMetre); - } - } - ); - put - ( - UnitTypes.AreaDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerSquareMetre); - } - } - ); - put - ( - UnitTypes.EnergyDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerCubicMetre); - } - } - ); - put - ( - UnitTypes.SpecificVolume, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetrePerKilogram); - } - } - ); - put - ( - UnitTypes.VolumetricFlowRate, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetrePerSecond); - } - } - ); - put - ( - UnitTypes.SurfaceTension, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerSquareMetre); - } - } - ); - put - ( - UnitTypes.SpecificWeight, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonPerCubicMetre); - } - } - ); - put - ( - UnitTypes.ThermalConductivity, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerMetrePerKelvin); - } - } - ); - put - ( - UnitTypes.ThermalConductance, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerKelvin); - } - } - ); - put - ( - UnitTypes.ThermalResistivity, new HashMap() - { - { - put(UnitSystems.SI, Units.MetreKelvinPerWatt); - } - } - ); - put - ( - UnitTypes.ThermalResistance, new HashMap() - { - { - put(UnitSystems.SI, Units.KelvinPerWatt); - } - } - ); - put - ( - UnitTypes.HeatTransferCoefficient, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSquareMetrePerKelvin); - } - } - ); - put - ( - UnitTypes.HeatFluxDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSquareMetre); - } - } - ); - put - ( - UnitTypes.Entropy, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerKelvin); - } - } - ); - put - ( - UnitTypes.ElectricFieldStrength, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonPerCoulomb); - } - } - ); - put - ( - UnitTypes.LinearElectricChargeDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerMetre); - } - } - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerSquareMetre); - } - } - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerCubicMetre); - } - } - ); - put - ( - UnitTypes.CurrentDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.AmperePerSquareMetre); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermittivity, new HashMap() - { - { - put(UnitSystems.SI, Units.FaradPerMetre); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermeability, new HashMap() - { - { - put(UnitSystems.SI, Units.HenryPerMetre); - } - } - ); - put - ( - UnitTypes.MolarEnergy, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerMole); - } - } - ); - put - ( - UnitTypes.MolarEntropy, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerMolePerKelvin); - } - } - ); - put - ( - UnitTypes.MolarVolume, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetrePerMole); - } - } - ); - put - ( - UnitTypes.MolarMass, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerMole); - } - } - ); - put - ( - UnitTypes.MolarConcentration, new HashMap() - { - { - put(UnitSystems.SI, Units.MolePerCubicMetre); - } - } - ); - put - ( - UnitTypes.MolalConcentration, new HashMap() - { - { - put(UnitSystems.SI, Units.MolePerKilogram); - } - } - ); - put - ( - UnitTypes.RadiantIntensity, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSteradian); - } - } - ); - put - ( - UnitTypes.Radiance, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSteradianPerSquareMetre); - } - } - ); - put - ( - UnitTypes.FuelEconomy, new HashMap() - { - { - put(UnitSystems.SI, Units.InverseSquareMetre); - put(UnitSystems.Imperial, Units.MilePerGallon); - } - } - ); - put - ( - UnitTypes.SoundExposure, new HashMap() - { - { - put(UnitSystems.SI, Units.SquarePascalSecond); - } - } - ); - put - ( - UnitTypes.SoundImpedance, new HashMap() - { - { - put(UnitSystems.SI, Units.PascalSecondPerCubicMetre); - } - } - ); - put - ( - UnitTypes.RotationalStiffness, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonMetrePerRadian); - } - } - ); - put - ( - UnitTypes.BitRate, new HashMap() - { - { - put(UnitSystems.SI, Units.BitPerSecond); - put(UnitSystems.Imperial, Units.BitPerSecond); - put(UnitSystems.CGS, Units.BitPerSecond); - } - } - ); - } - } - }; - - NonBasicCompoundsToSkip = new ArrayList() - {{ - add(Units.Centimetre); - }}; - - AllNonBasicCompounds = new HashMap>() - { - { - { - //--- Length - put - ( - Units.Centimetre, //Not exactly a compound, but included here for consistency reasons. - new ArrayList() {{ add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi)); }} - ); - - //--- Area - put - ( - Units.SquareInch, - new ArrayList() {{ add(new UnitPart(Units.Inch, 2)); }} - ); - put - ( - Units.SquareRod, - new ArrayList() {{ add(new UnitPart(Units.Rod, 2)); }} - ); - put - ( - Units.SquarePerch, - new ArrayList() {{ add(new UnitPart(Units.Perch, 2)); }} - ); - put - ( - Units.SquarePole, - new ArrayList() {{ add(new UnitPart(Units.Pole, 2)); }} - ); - - //--- Volume - put - ( - Units.CubicInch, - new ArrayList() {{ add(new UnitPart(Units.Inch, 3)); }} - ); - - //--- Velocity - put - ( - Units.InchPerSecond, - new ArrayList() - {{ - add(new UnitPart(Units.Inch)); - add(new UnitPart(Units.Second, -1)); - }} - ); - put - ( - Units.Knot, - new ArrayList() - {{ - add(new UnitPart(Units.NauticalMile)); - add(new UnitPart(Units.Hour, -1)); - }} - ); - put - ( - Units.KilometrePerHour, - new ArrayList() - {{ - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Kilo)); - add(new UnitPart(Units.Hour, -1)); - }} - ); - put - ( - Units.MilePerHour, - new ArrayList() - {{ - add(new UnitPart(Units.Mile)); - add(new UnitPart(Units.Hour, -1)); - }} - ); - - //--- Acceleration - put - ( - Units.InchPerSquareSecond, - new ArrayList() - {{ - add(new UnitPart(Units.Inch)); - add(new UnitPart(Units.Second, -2)); - }} - ); - - //--- Energy - put - ( - Units.WattHour, - new ArrayList() - {{ - add(new UnitPart(Units.Metre, 2)); - add(UnitPartInternal.NewUnitPart(Units.Gram, SIPrefixValues.Kilo)); - add(new UnitPart(Units.Hour)); - add(new UnitPart(Units.Second, -3)); - }} - ); - - //--- Pressure - put - ( - Units.TechnicalAtmosphere, - new ArrayList() - {{ - add(new UnitPart(Units.Kilopond)); - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi, -2)); - }} - ); - put - ( - Units.PoundforcePerSquareInch, - new ArrayList() - {{ - add(new UnitPart(Units.PoundForce)); - add(new UnitPart(Units.Inch, -2)); - }} - ); - put - ( - Units.PoundforcePerSquareFoot, - new ArrayList() - {{ - add(new UnitPart(Units.PoundForce)); - add(new UnitPart(Units.Foot, -2)); - }} - ); - put - ( - Units.KipPerSquareInch, - new ArrayList() - {{ - add(new UnitPart(Units.Kip)); - add(new UnitPart(Units.Inch, -2)); - }} - ); - put - ( - Units.Barye, - new ArrayList() - {{ - add(new UnitPart(Units.Dyne)); - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi, -2)); - }} - ); - - //--- Angular velocity - put - ( - Units.RevolutionPerMinute, - new ArrayList() - {{ - add(new UnitPart(Units.Revolution)); - add(new UnitPart(Units.Minute, -1)); - }} - ); - - //--- Solid Angle - put - ( - Units.SquareDegree, - new ArrayList() - {{ - add(new UnitPart(Units.Degree, 2)); - }} - ); - - //--- Electric Charge - put - ( - Units.AmpereHour, - new ArrayList() - {{ - add(new UnitPart(Units.Ampere)); - add(new UnitPart(Units.Hour)); - }} - ); - - //--- Magnetic Field B - put - ( - Units.Gauss, - new ArrayList() - {{ - add(new UnitPart(Units.Maxwell)); - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi, -2)); - }} - ); - - //--- Luminous Energy - put - ( - Units.Talbot, - new ArrayList() - {{ - add(new UnitPart(Units.Lumen)); - add(new UnitPart(Units.Second)); - }} - ); - - //--- Luminance - put - ( - Units.Nit, - new ArrayList() - {{ - add(new UnitPart(Units.Candela)); - add(new UnitPart(Units.Metre, -2)); - }} - ); - - //--- Fuel Economy - put - ( - Units.USCSMilePerGallon, - new ArrayList() - {{ - add(new UnitPart(Units.Mile)); - add(new UnitPart(Units.LiquidGallon, -1)); - }} - ); - put - ( - Units.KilometrePerLitre, - new ArrayList() - {{ - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Kilo)); - add(new UnitPart(Units.Litre, -1)); - }} - ); - } - } - }; - - AllBasicUnits = new HashMap>() - { - { - { - put - ( - UnitTypes.Length, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Metre)); - put(UnitSystems.CGS, new BasicUnit(Units.Metre, SIPrefixValues.Centi)); - put(UnitSystems.Imperial, new BasicUnit(Units.Foot)); - } - } - ); - put - ( - UnitTypes.Area, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.SquareMetre)); - put(UnitSystems.CGS, new BasicUnit(Units.SquareCentimetre)); - put(UnitSystems.Imperial, new BasicUnit(Units.SquareFoot)); - } - } - ); - put - ( - UnitTypes.Volume, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.CubicMetre)); - put(UnitSystems.CGS, new BasicUnit(Units.CubicCentimetre)); - put(UnitSystems.Imperial, new BasicUnit(Units.CubicFoot)); - } - } - ); - put - ( - UnitTypes.Mass, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Gram, SIPrefixValues.Kilo)); - put(UnitSystems.CGS, new BasicUnit(Units.Gram)); - put(UnitSystems.Imperial, new BasicUnit(Units.Pound)); - } - } - ); - put - ( - UnitTypes.Time, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Second)); - put(UnitSystems.CGS, new BasicUnit(Units.Second)); - put(UnitSystems.Imperial, new BasicUnit(Units.Second)); - } - } - ); - put - ( - UnitTypes.Force, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Newton)); - put(UnitSystems.CGS, new BasicUnit(Units.Dyne)); - put(UnitSystems.Imperial, new BasicUnit(Units.PoundForce)); - } - } - ); - put - ( - UnitTypes.Energy, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Joule)); - put(UnitSystems.CGS, new BasicUnit(Units.Erg)); - put(UnitSystems.Imperial, new BasicUnit(Units.BritishThermalUnit)); - } - } - ); - put - ( - UnitTypes.Power, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Watt)); - put(UnitSystems.CGS, new BasicUnit(Units.ErgPerSecond)); - put(UnitSystems.Imperial, new BasicUnit(Units.Horsepower)); - } - } - ); - put - ( - UnitTypes.Temperature, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Kelvin)); - put(UnitSystems.Imperial, new BasicUnit(Units.DegreeFahrenheit)); - put(UnitSystems.CGS, new BasicUnit(Units.Kelvin)); - } - } - ); - put - ( - UnitTypes.Angle, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Radian)); - put(UnitSystems.CGS, new BasicUnit(Units.Radian)); - put(UnitSystems.Imperial, new BasicUnit(Units.Radian)); - } - } - ); - put - ( - UnitTypes.SolidAngle, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Steradian)); - put(UnitSystems.CGS, new BasicUnit(Units.Steradian)); - put(UnitSystems.Imperial, new BasicUnit(Units.Steradian)); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Ampere)); - put(UnitSystems.CGS, new BasicUnit(Units.Ampere)); - put(UnitSystems.Imperial, new BasicUnit(Units.Ampere)); - } - } - ); - put - ( - UnitTypes.LuminousIntensity, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Candela)); - put(UnitSystems.CGS, new BasicUnit(Units.Candela)); - put(UnitSystems.Imperial, new BasicUnit(Units.Candela)); - } - } - ); - put - ( - UnitTypes.AmountOfSubstance, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Mole)); - put(UnitSystems.CGS, new BasicUnit(Units.Mole)); - put(UnitSystems.Imperial, new BasicUnit(Units.Mole)); - } - } - ); - put - ( - UnitTypes.Information, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Bit)); - put(UnitSystems.CGS, new BasicUnit(Units.Bit)); - put(UnitSystems.Imperial, new BasicUnit(Units.Bit)); - } - } - ); - } - } - }; - - return ""; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/16/60c25fdae54c00171118892245944c7f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/16/60c25fdae54c00171118892245944c7f deleted file mode 100644 index 0810233..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/16/60c25fdae54c00171118892245944c7f +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/16/80de70b4504c00171860ae6a5189088d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/16/80de70b4504c00171860ae6a5189088d deleted file mode 100644 index 95df9b9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/16/80de70b4504c00171860ae6a5189088d +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/17/7057519db14a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/17/7057519db14a00171059ebc16969059f deleted file mode 100644 index 0d81e91..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/17/7057519db14a00171059ebc16969059f +++ /dev/null @@ -1,1059 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - UnitInfo test22 = Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - System.out.println(test22.Value); - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/18/c0f64347b24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/18/c0f64347b24a00171059ebc16969059f deleted file mode 100644 index dfab513..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/18/c0f64347b24a00171059ebc16969059f +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/19/9000ba9b5c4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/19/9000ba9b5c4c0017146ede6da4ae5d42 deleted file mode 100644 index 45f8302..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/19/9000ba9b5c4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,17 +0,0 @@ -package test0; - -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP("1m"); - UnitP test2 = new UnitP(1.0, "1m2/m"); - - if(test.equals(test2)) - { - System.out.println("Is OK"); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/19/900f97246f4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/19/900f97246f4c00171838d4a3813404a0 deleted file mode 100644 index 1267c17..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/19/900f97246f4c00171838d4a3813404a0 +++ /dev/null @@ -1,251 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return null; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || filter == null) return new ArrayList(); - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), filter, defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1a/407856665a4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1a/407856665a4c0017146ede6da4ae5d42 deleted file mode 100644 index 1fb8280..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1a/407856665a4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1171 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - public int compareTo(UnitP other) - { - // TODO Auto-generated method stub - return 0; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1a/90e18b8cab4a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1a/90e18b8cab4a00171059ebc16969059f deleted file mode 100644 index 87f0d76..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1a/90e18b8cab4a00171059ebc16969059f +++ /dev/null @@ -1,1384 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - - System.out.println(tempInfo.Value + " " + tempInfo.BaseTenExponent); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1b/109b886d604c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1b/109b886d604c0017146ede6da4ae5d42 deleted file mode 100644 index 0bcde0a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1b/109b886d604c0017146ede6da4ae5d42 +++ /dev/null @@ -1,26 +0,0 @@ -package test0; - -import java.util.ArrayList; -import java.util.Collections; - -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - ArrayList tests = new ArrayList(); - tests.add(new UnitP("1m")); - tests.add(new UnitP("10m2")); - tests.add(new UnitP("5m")); - tests.add(new UnitP("2m")); - - Collections.sort(tests); - - for (UnitP item: tests) - { - System.out.println(item.ValueAndUnitString); - } - - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1c/c03a825b2b4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1c/c03a825b2b4a001712d4a4f7b050cac8 deleted file mode 100644 index 3f1f1b2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1c/c03a825b2b4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1166 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - System.out.println(unitP2.UnitInfo.Parts.get(0).Unit); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1c/d0ed5a03684c00171a25ec0b13e7f3ac b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1c/d0ed5a03684c00171a25ec0b13e7f3ac deleted file mode 100644 index f9825dc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1c/d0ed5a03684c00171a25ec0b13e7f3ac +++ /dev/null @@ -1,219 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -import java.util.AbstractMap; - -public class Prefix implements Comparable -{ - /**Name of the unit prefix.**/ - public final String Name; - /**Symbol of the unit prefix.**/ - public final String Symbol; - /**Multiplying factor associated with the unit prefix.**/ - public final double Factor; - /**Type of the unit prefix.**/ - public final PrefixTypes Type; - /**Usage conditions of the unit prefix.**/ - public final PrefixUsageTypes PrefixUsage; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /**Initialises a new Prefix instance.**/ - public Prefix() - { - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - PrefixUsage = PrefixUsageTypes.DefaultUsage; - } - - /** - Initialises a new Prefix instance. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - } - - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor) - { - this(factor, PrefixUsageTypes.DefaultUsage); - } - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(factor, ""); - - if (Type != PrefixTypes.None) - { - Factor = factor; - Name = GetName(Type, Factor); - - Symbol = Linq.FirstOrDefaultDict - ( - Type == PrefixTypes.SI ? HCPrefixes.AllSIPrefixSymbols : - HCPrefixes.AllBinaryPrefixSymbols, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(null, 0.0) - ) - .getKey(); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol) - { - this(symbol, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(1.0, symbol); - - if (Type != PrefixTypes.None) - { - Symbol = symbol; - Factor = - ( - Type == PrefixTypes.SI ? - HCPrefixes.AllSIPrefixSymbols.get(symbol) : - HCPrefixes.AllBinaryPrefixSymbols.get(symbol) - ); - Name = GetName(Type, Factor); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name prefix Prefix variable whose information will be used. - **/ - public Prefix(Prefix prefix) - { - if (prefix == null) prefix = new Prefix(); - - Name = prefix.Name; - Symbol = prefix.Symbol; - Factor = prefix.Factor; - Type = prefix.Type; - PrefixUsage = prefix.PrefixUsage; - } - - private static PrefixTypes GetType(double factor, String symbol) - { - PrefixTypes outType = PrefixTypes.None; - if (factor == 1.0 && symbol == "") return outType; - - if (factor != 1.0) - { - if (HCPrefixes.AllSIPrefixes.containsValue(factor)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixes.containsValue(factor)) - { - outType = PrefixTypes.Binary; - } - } - else - { - if (HCPrefixes.AllSIPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.Binary; - } - } - - return outType; - } - - private static String GetName(PrefixTypes type, double factor) - { - return - ( - type == PrefixTypes.SI ? - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) : - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - ) - .getKey().toString(); - } - - @Override - ///Compares the current instance against another Prefix one. - ///The other Prefix instance. - public int compareTo(Prefix other) - { - return new Double(this.Factor).compareTo(other.Factor); - } - - @Override - ///Determines whether the current Prefix instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((Prefix)obj); - } - - boolean Equals(Prefix other) - { - return - ( - other == null ? false : - Equals.PrefixesAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this Prefix instance. - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1f/6052e36e9a4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1f/6052e36e9a4a00171930ee4d171ed0de deleted file mode 100644 index e74dd4a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1f/6052e36e9a4a00171930ee4d171ed0de +++ /dev/null @@ -1,1034 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1f/908416f45f4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1f/908416f45f4c0017146ede6da4ae5d42 deleted file mode 100644 index f5cf0e4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/1f/908416f45f4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,218 +0,0 @@ -package UnitParser; - -import java.util.AbstractMap; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -public class Prefix implements Comparable -{ - /**Name of the unit prefix.**/ - public final String Name; - /**Symbol of the unit prefix.**/ - public final String Symbol; - /**Multiplying factor associated with the unit prefix.**/ - public final double Factor; - /**Type of the unit prefix.**/ - public final PrefixTypes Type; - /**Usage conditions of the unit prefix.**/ - public final PrefixUsageTypes PrefixUsage; - - /**Initialises a new Prefix instance.**/ - public Prefix() - { - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - PrefixUsage = PrefixUsageTypes.DefaultUsage; - } - - /** - Initialises a new Prefix instance. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - } - - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor) - { - this(factor, PrefixUsageTypes.DefaultUsage); - } - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(factor, ""); - - if (Type != PrefixTypes.None) - { - Factor = factor; - Name = GetName(Type, Factor); - - Symbol = Linq.FirstOrDefaultDict - ( - Type == PrefixTypes.SI ? HCPrefixes.AllSIPrefixSymbols : - HCPrefixes.AllBinaryPrefixSymbols, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(null, 0.0) - ) - .getKey(); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol) - { - this(symbol, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(1.0, symbol); - - if (Type != PrefixTypes.None) - { - Symbol = symbol; - Factor = - ( - Type == PrefixTypes.SI ? - HCPrefixes.AllSIPrefixSymbols.get(symbol) : - HCPrefixes.AllBinaryPrefixSymbols.get(symbol) - ); - Name = GetName(Type, Factor); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name prefix Prefix variable whose information will be used. - **/ - public Prefix(Prefix prefix) - { - if (prefix == null) prefix = new Prefix(); - - Name = prefix.Name; - Symbol = prefix.Symbol; - Factor = prefix.Factor; - Type = prefix.Type; - PrefixUsage = prefix.PrefixUsage; - } - - private static PrefixTypes GetType(double factor, String symbol) - { - PrefixTypes outType = PrefixTypes.None; - if (factor == 1.0 && symbol == "") return outType; - - if (factor != 1.0) - { - if (HCPrefixes.AllSIPrefixes.containsValue(factor)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixes.containsValue(factor)) - { - outType = PrefixTypes.Binary; - } - } - else - { - if (HCPrefixes.AllSIPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.Binary; - } - } - - return outType; - } - - private static String GetName(PrefixTypes type, double factor) - { - return - ( - type == PrefixTypes.SI ? - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) : - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - ) - .getKey().toString(); - } - - public int CompareTo(Prefix other) - { - return new Double(this.Factor).compareTo(new Double(other.Factor)); - } - - public boolean Equals(Prefix other) - { - return - ( - other == null ? false : - Equals.PrefixesAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((Prefix)obj); - } - - @Override - public int hashCode() { return 0; } - - @Override - public int compareTo(Prefix o) - { - // TODO Auto-generated method stub - return 0; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/20/90f9ec03f54c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/20/90f9ec03f54c00171048b3f61ecb42d3 deleted file mode 100644 index ba7ccd0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/20/90f9ec03f54c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1229 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - @return Current instance converted to targetUnit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return Current instance converted to targetUnit and targetPrefix. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - @return Current instance converted to targetUnitString. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance unit. - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the unit of the current instance. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/20/d039a043784c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/20/d039a043784c00171945f16efe0d9b5d deleted file mode 100644 index 8804712..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/20/d039a043784c00171945f16efe0d9b5d +++ /dev/null @@ -1,136 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = - ( - improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - UnitInfo.Value - ); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/22/109b8b405d4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/22/109b8b405d4c0017146ede6da4ae5d42 deleted file mode 100644 index d5ca744..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/22/109b8b405d4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,162 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return (first.Error.equals(second.Error)); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type.equals(ErrorTypes.None) || secondInfo.Error.Type.equals(ErrorTypes.None)) - { - return firstInfo.Error.Type.equals(secondInfo.Error.Type); - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent.equals(secondInfo.BaseTenExponent) && - firstInfo.Value.equals(secondInfo.Value) - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling.equals(second.ExceptionHandling) && - first.Type.equals(second.Type) - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/23/8030e9db404c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/23/8030e9db404c00171eb8e3cba3fc21fa deleted file mode 100644 index 8586c47..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/23/8030e9db404c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,68 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //Emulating the conditions of the original C# version where decimal numbers cannot be parsed as integer. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input) throws ParseException - { - //Locale.US because of being the best equivalence for CultureInfo.InvariantCulture in the original C# code. - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/25/400d13c45a4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/25/400d13c45a4c0017146ede6da4ae5d42 deleted file mode 100644 index aa8c188..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/25/400d13c45a4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1180 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/25/b092f87e6f4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/25/b092f87e6f4c00171838d4a3813404a0 deleted file mode 100644 index 5b009ce..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/25/b092f87e6f4c00171838d4a3813404a0 +++ /dev/null @@ -1,251 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return null; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || filter == null) return new ArrayList(); - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/26/00ea03d0f74c00171d64cefe2267baa0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/26/00ea03d0f74c00171d64cefe2267baa0 deleted file mode 100644 index 0810233..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/26/00ea03d0f74c00171d64cefe2267baa0 +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/26/5027efa3a84a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/26/5027efa3a84a00171059ebc16969059f deleted file mode 100644 index d062520..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/26/5027efa3a84a00171059ebc16969059f +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/27/104edf692f4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/27/104edf692f4a001712d4a4f7b050cac8 deleted file mode 100644 index dcdc258..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/27/104edf692f4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1859 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/29/0001fadc8f4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/29/0001fadc8f4a00171930ee4d171ed0de deleted file mode 100644 index ce62290..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/29/0001fadc8f4a00171930ee4d171ed0de +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - System.out.println(normalised.get(0).Value + " " + normalised.get(0).BaseTenExponent + " " + normalised.get(0).Prefix.Factor + " -- " + normalised.get(1).Value + " " + normalised.get(1).BaseTenExponent + " " + normalised.get(1).Prefix.Factor); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2a/60f3cb942c4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2a/60f3cb942c4a001712d4a4f7b050cac8 deleted file mode 100644 index ee6fd79..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2a/60f3cb942c4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2b/20dd8300b44a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2b/20dd8300b44a00171059ebc16969059f deleted file mode 100644 index 790a517..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2b/20dd8300b44a00171059ebc16969059f +++ /dev/null @@ -1,1062 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - UnitInfo test = Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - System.out.println(test.Value + " asdfasdf"); - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2b/d02e83aaf24c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2b/d02e83aaf24c00171048b3f61ecb42d3 deleted file mode 100644 index 2d523d3..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2b/d02e83aaf24c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1216 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList variable including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList variable including all the primary string representations associated with unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2b/f0987ceb2b4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2b/f0987ceb2b4a001712d4a4f7b050cac8 deleted file mode 100644 index cfe3259..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2b/f0987ceb2b4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1033 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - System.out.println(unitString); - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2c/b09948695b4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2c/b09948695b4c0017146ede6da4ae5d42 deleted file mode 100644 index b8212b0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2c/b09948695b4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1197 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/0038332f2b4c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/0038332f2b4c00171ae7fcf2c321c986 deleted file mode 100644 index 121348c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/0038332f2b4c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = (int)Math.signum(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - System.out.println(unitInfo.Parts.get(i).Exponent); - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/007acd942c4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/007acd942c4a001712d4a4f7b050cac8 deleted file mode 100644 index 0d6fa89..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/007acd942c4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,135 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - System.out.println(originalUnitString); - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = - ( - improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - UnitInfo.Value - ); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/10b9d961b24b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/10b9d961b24b00171c69d98bf667dda6 deleted file mode 100644 index 7ff732e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/10b9d961b24b00171c69d98bf667dda6 +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/c06fdd99984a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/c06fdd99984a00171930ee4d171ed0de deleted file mode 100644 index b7def56..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2d/c06fdd99984a00171930ee4d171ed0de +++ /dev/null @@ -1,570 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - - UnitInfo temp = PerformManagedOperationAddition(firstInfo, secondInfo, operation); - System.out.println(temp.Value + " " + temp.BaseTenExponent + " " + temp.Prefix.Factor); - - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2e/602694a79b4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2e/602694a79b4a00171930ee4d171ed0de deleted file mode 100644 index fd95877..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2e/602694a79b4a00171930ee4d171ed0de +++ /dev/null @@ -1,1858 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - System.out.println(prefixFactor); - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - //System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2e/b0e698a3794c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2e/b0e698a3794c00171945f16efe0d9b5d deleted file mode 100644 index ac735b7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2e/b0e698a3794c00171945f16efe0d9b5d +++ /dev/null @@ -1,2561 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import InternalUnitParser.Classes.*; -import UnitParser.*; - -import java.util.HashMap; -import java.util.ArrayList; - - -@SuppressWarnings("serial") -public class HCCompounds -{ - /** - Contains the definitions of all the supported compounds, understood as units formed by other units - and/or variations (e.g., exponents different than 1) of them. - In order to be as efficient as possible, AllCompounds ignores the difference between dividable and - non-dividable units. For example: N is formed by kg*m/s2, exactly what this collection expects; on the - other hand, lbf isn't formed by the expected lb*ft/s2. In any case, note that this "faulty" format is - only used internally, never shown to the user. - NOTE: the order of the compounds within each type does matter. The first position is reserved for the main - fully-expanded version (e.g., mass*length/time2 for force). In the second position, the compound basic - units (e.g., force) are expected to have their 1-part version (e.g., 1 force part for force). - **/ - public static HashMap> AllCompounds; - /** - Contains all the named compounds defined by the basic units for the given type/system. - For example, Newton is formed by kg*m/s^2, the basic mass*length/time units in SI, and that's why it belongs here. - **/ - public static HashMap> AllBasicCompounds; - - //Roughly speaking, AllNonBasicCompounds is a container of somehow exceptional situations. - //Some of these units (e.g., centimetre) shouldn't be matched when looking for valid compounds. - public static ArrayList NonBasicCompoundsToSkip; - - //Contains the definition (i.e., UnitPart[] containing their defining units) of all the supported named - //compounds except the ones defined by the corresponding basic units (included in AllBasicCompounds). - public static HashMap> AllNonBasicCompounds; - - //Classifies all the basic units on account of their types and systems. - //Note that these units don't meet the most intuitive interpretation of the basic unit idea. - //That is, they aren't just the most basic constituent of compounds (i.e., impossible to be - //further divided), but also compounds. The reason for this a-priori abnormal configuration - //is that they aren't just used to model SI/CGS compounds, but also Imperial/USCS ones. - //For example: the SI force unit (N) can be defined on account of properly-speaking basic units, - //but the Imperial/USCS version (lbf) cannot. - public static HashMap> AllBasicUnits; - - public static void Start() - { - AllCompounds = new HashMap>() - { - { - { - put - ( - UnitTypes.Area, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Length, 2)); }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Area)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Volume, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Length, 3)); }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Volume)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Velocity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Acceleration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Force, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Force)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Energy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Energy)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Power, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Power)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Pressure, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -1)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Frequency, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Time, -1)); }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricCharge, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricVoltage, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricResistance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricResistivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricConductance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricConductivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricCapacitance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 4)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricInductance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricDipoleMoment, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time, 1)); - add(new CompoundPart(UnitTypes.Length, 1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Wavenumber, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Length, -1)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Viscosity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -1)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.KinematicViscosity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Momentum, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AngularVelocity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Angle)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AngularAcceleration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Angle)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AngularMomentum, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MomentOfInertia, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SolidAngle, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Angle, 2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.LuminousFlux, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.SolidAngle)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.LuminousEnergy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.SolidAngle)); - add(new CompoundPart(UnitTypes.Time)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Luminance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Illuminance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.SolidAngle)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MagneticFlux, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MagneticFieldB, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MagneticFieldH, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Length, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AbsorbedDose, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AbsorbedDoseRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.EquivalentDose, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Exposure, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Mass, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.CatalyticActivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.CatalyticActivityConcentration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Time, -1)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Jerk, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MassFlowRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Density, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AreaDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.EnergyDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -1)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SpecificVolume, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.Mass, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.VolumetricFlowRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SurfaceTension, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SpecificWeight, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalConductivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalConductance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalResistivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Temperature)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalResistance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Temperature)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.HeatTransferCoefficient, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.HeatFluxDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Entropy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricFieldStrength, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.LinearElectricChargeDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Length, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.CurrentDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectromagneticPermittivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 4)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectromagneticPermeability, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 1)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarEnergy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarEntropy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarVolume, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarMass, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarConcentration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolalConcentration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Mass, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.RadiantIntensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.SolidAngle, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Radiance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.SolidAngle, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.FuelEconomy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SoundExposure, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass, 2)); - add(new CompoundPart(UnitTypes.Length, -2)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SoundImpedance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -4)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.RotationalStiffness, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.Angle, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.BitRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Information)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - } - } - }; - - AllBasicCompounds = new HashMap>() - { - { - { - put - ( - UnitTypes.Area, new HashMap() - { - { - put(UnitSystems.SI, Units.SquareMetre); - put(UnitSystems.CGS, Units.SquareCentimetre); - put(UnitSystems.Imperial, Units.SquareFoot); - } - } - ); - put - ( - UnitTypes.Volume, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetre); - put(UnitSystems.CGS, Units.CubicCentimetre); - put(UnitSystems.Imperial, Units.CubicFoot); - } - } - ); - put - ( - UnitTypes.Velocity, new HashMap() - { - { - put(UnitSystems.SI, Units.MetrePerSecond); - put(UnitSystems.CGS, Units.CentimetrePerSecond); - put(UnitSystems.Imperial, Units.FootPerSecond); - } - } - ); - put - ( - UnitTypes.Acceleration, new HashMap() - { - { - put(UnitSystems.SI, Units.MetrePerSquareSecond); - put(UnitSystems.CGS, Units.Gal); - put(UnitSystems.Imperial, Units.FootPerSquareSecond); - } - } - ); - put - ( - UnitTypes.Force, new HashMap() - { - { - put(UnitSystems.SI, Units.Newton); - put(UnitSystems.CGS, Units.Dyne); - put(UnitSystems.Imperial, Units.Poundal); - } - } - ); - put - ( - UnitTypes.Energy, new HashMap() - { - { - put(UnitSystems.SI, Units.Joule); - put(UnitSystems.CGS, Units.Erg); - } - } - ); - put - ( - UnitTypes.Power, new HashMap() - { - { - put(UnitSystems.SI, Units.Watt); - put(UnitSystems.CGS, Units.ErgPerSecond); - } - } - ); - put - ( - UnitTypes.Pressure, new HashMap() - { - { - put(UnitSystems.SI, Units.Pascal); - put(UnitSystems.CGS, Units.Barye); - put(UnitSystems.Imperial, Units.PoundforcePerSquareFoot); - } - } - ); - put - ( - UnitTypes.Frequency, new HashMap() - { - { - put(UnitSystems.SI, Units.Hertz); - } - } - ); - put - ( - UnitTypes.ElectricCharge, new HashMap() - { - { - put(UnitSystems.SI, Units.Coulomb); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, new HashMap() - { - { - put(UnitSystems.SI, Units.Ampere); - } - } - ); - put - ( - UnitTypes.ElectricVoltage, new HashMap() - { - { - put(UnitSystems.SI, Units.Volt); - } - } - ); - put - ( - UnitTypes.ElectricResistance, new HashMap() - { - { - put(UnitSystems.SI, Units.Ohm); - } - } - ); - put - ( - UnitTypes.ElectricResistivity, new HashMap() - { - { - put(UnitSystems.SI, Units.OhmMetre); - } - } - ); - put - ( - UnitTypes.ElectricConductance, new HashMap() - { - { - put(UnitSystems.SI, Units.Siemens); - } - } - ); - put - ( - UnitTypes.ElectricConductivity, new HashMap() - { - { - put(UnitSystems.SI, Units.SiemensPerMetre); - } - } - ); - put - ( - UnitTypes.ElectricCapacitance, new HashMap() - { - { - put(UnitSystems.SI, Units.Farad); - } - } - ); - put - ( - UnitTypes.ElectricInductance, new HashMap() - { - { - put(UnitSystems.SI, Units.Henry); - } - } - ); - put - ( - UnitTypes.ElectricDipoleMoment, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombMetre); - } - } - ); - put - ( - UnitTypes.Wavenumber, new HashMap() - { - { - put(UnitSystems.SI, Units.ReciprocalMetre); - put(UnitSystems.CGS, Units.Kayser); - } - } - ); - put - ( - UnitTypes.Viscosity, new HashMap() - { - { - put(UnitSystems.SI, Units.PascalSecond); - put(UnitSystems.CGS, Units.Poise); - } - } - ); - put - ( - UnitTypes.KinematicViscosity, new HashMap() - { - { - put(UnitSystems.SI, Units.SquareMetrePerSecond); - put(UnitSystems.CGS, Units.Stokes); - } - } - ); - put - ( - UnitTypes.Momentum, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonSecond); - } - } - ); - put - ( - UnitTypes.AngularVelocity, new HashMap() - { - { - put(UnitSystems.SI, Units.RadianPerSecond); - } - } - ); - put - ( - UnitTypes.AngularAcceleration, new HashMap() - { - { - put(UnitSystems.SI, Units.RadianPerSquareSecond); - } - } - ); - put - ( - UnitTypes.AngularMomentum, new HashMap() - { - { - put(UnitSystems.SI, Units.JouleSecond); - } - } - ); - put - ( - UnitTypes.MomentOfInertia, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramSquareMetre); - } - } - ); - put - ( - UnitTypes.SolidAngle, new HashMap() - { - { - put(UnitSystems.SI, Units.Steradian); - } - } - ); - put - ( - UnitTypes.LuminousFlux, new HashMap() - { - { - put(UnitSystems.SI, Units.Lumen); - } - } - ); - put - ( - UnitTypes.LuminousEnergy, new HashMap() - { - { - put(UnitSystems.SI, Units.LumenSecond); - } - } - ); - put - ( - UnitTypes.Luminance, new HashMap() - { - { - put(UnitSystems.SI, Units.CandelaPerSquareMetre); - put(UnitSystems.CGS, Units.Stilb); - } - } - ); - put - ( - UnitTypes.Illuminance, new HashMap() - { - { - put(UnitSystems.SI, Units.Lux); - put(UnitSystems.CGS, Units.Phot); - put(UnitSystems.Imperial, Units.FootCandle); - } - } - ); - put - ( - UnitTypes.MagneticFlux, new HashMap() - { - { - put(UnitSystems.SI, Units.Weber); - } - } - ); - put - ( - UnitTypes.MagneticFieldB, new HashMap() - { - { - put(UnitSystems.SI, Units.Tesla); - } - } - ); - put - ( - UnitTypes.AbsorbedDose, new HashMap() - { - { - put(UnitSystems.SI, Units.Gray); - } - } - ); - put - ( - UnitTypes.AbsorbedDoseRate, new HashMap() - { - { - put(UnitSystems.SI, Units.GrayPerSecond); - } - } - ); - put - ( - UnitTypes.EquivalentDose, new HashMap() - { - { - put(UnitSystems.SI, Units.Sievert); - } - } - ); - put - ( - UnitTypes.Exposure, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerKilogram); - put(UnitSystems.CGS, Units.Roentgen); - } - } - ); - put - ( - UnitTypes.CatalyticActivity, new HashMap() - { - { - put(UnitSystems.SI, Units.Katal); - } - } - ); - put - ( - UnitTypes.CatalyticActivityConcentration, new HashMap() - { - { - put(UnitSystems.SI, Units.KatalPerCubicMetre); - } - } - ); - put - ( - UnitTypes.Jerk, new HashMap() - { - { - put(UnitSystems.SI, Units.MetrePerCubicSecond); - } - } - ); - put - ( - UnitTypes.MassFlowRate, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerSecond); - } - } - ); - put - ( - UnitTypes.Density, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerCubicMetre); - } - } - ); - put - ( - UnitTypes.AreaDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerSquareMetre); - } - } - ); - put - ( - UnitTypes.EnergyDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerCubicMetre); - } - } - ); - put - ( - UnitTypes.SpecificVolume, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetrePerKilogram); - } - } - ); - put - ( - UnitTypes.VolumetricFlowRate, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetrePerSecond); - } - } - ); - put - ( - UnitTypes.SurfaceTension, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerSquareMetre); - } - } - ); - put - ( - UnitTypes.SpecificWeight, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonPerCubicMetre); - } - } - ); - put - ( - UnitTypes.ThermalConductivity, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerMetrePerKelvin); - } - } - ); - put - ( - UnitTypes.ThermalConductance, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerKelvin); - } - } - ); - put - ( - UnitTypes.ThermalResistivity, new HashMap() - { - { - put(UnitSystems.SI, Units.MetreKelvinPerWatt); - } - } - ); - put - ( - UnitTypes.ThermalResistance, new HashMap() - { - { - put(UnitSystems.SI, Units.KelvinPerWatt); - } - } - ); - put - ( - UnitTypes.HeatTransferCoefficient, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSquareMetrePerKelvin); - } - } - ); - put - ( - UnitTypes.HeatFluxDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSquareMetre); - } - } - ); - put - ( - UnitTypes.Entropy, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerKelvin); - } - } - ); - put - ( - UnitTypes.ElectricFieldStrength, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonPerCoulomb); - } - } - ); - put - ( - UnitTypes.LinearElectricChargeDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerMetre); - } - } - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerSquareMetre); - } - } - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerCubicMetre); - } - } - ); - put - ( - UnitTypes.CurrentDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.AmperePerSquareMetre); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermittivity, new HashMap() - { - { - put(UnitSystems.SI, Units.FaradPerMetre); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermeability, new HashMap() - { - { - put(UnitSystems.SI, Units.HenryPerMetre); - } - } - ); - put - ( - UnitTypes.MolarEnergy, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerMole); - } - } - ); - put - ( - UnitTypes.MolarEntropy, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerMolePerKelvin); - } - } - ); - put - ( - UnitTypes.MolarVolume, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetrePerMole); - } - } - ); - put - ( - UnitTypes.MolarMass, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerMole); - } - } - ); - put - ( - UnitTypes.MolarConcentration, new HashMap() - { - { - put(UnitSystems.SI, Units.MolePerCubicMetre); - } - } - ); - put - ( - UnitTypes.MolalConcentration, new HashMap() - { - { - put(UnitSystems.SI, Units.MolePerKilogram); - } - } - ); - put - ( - UnitTypes.RadiantIntensity, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSteradian); - } - } - ); - put - ( - UnitTypes.Radiance, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSteradianPerSquareMetre); - } - } - ); - put - ( - UnitTypes.FuelEconomy, new HashMap() - { - { - put(UnitSystems.SI, Units.InverseSquareMetre); - put(UnitSystems.Imperial, Units.MilePerGallon); - } - } - ); - put - ( - UnitTypes.SoundExposure, new HashMap() - { - { - put(UnitSystems.SI, Units.SquarePascalSecond); - } - } - ); - put - ( - UnitTypes.SoundImpedance, new HashMap() - { - { - put(UnitSystems.SI, Units.PascalSecondPerCubicMetre); - } - } - ); - put - ( - UnitTypes.RotationalStiffness, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonMetrePerRadian); - } - } - ); - put - ( - UnitTypes.BitRate, new HashMap() - { - { - put(UnitSystems.SI, Units.BitPerSecond); - put(UnitSystems.Imperial, Units.BitPerSecond); - put(UnitSystems.CGS, Units.BitPerSecond); - } - } - ); - } - } - }; - - NonBasicCompoundsToSkip = new ArrayList() - {{ - add(Units.Centimetre); - }}; - - AllNonBasicCompounds = new HashMap>() - { - { - { - //--- Length - put - ( - Units.Centimetre, //Not exactly a compound, but included here for consistency reasons. - new ArrayList() {{ add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi)); }} - ); - - //--- Area - put - ( - Units.SquareInch, - new ArrayList() {{ add(new UnitPart(Units.Inch, 2)); }} - ); - put - ( - Units.SquareRod, - new ArrayList() {{ add(new UnitPart(Units.Rod, 2)); }} - ); - put - ( - Units.SquarePerch, - new ArrayList() {{ add(new UnitPart(Units.Perch, 2)); }} - ); - put - ( - Units.SquarePole, - new ArrayList() {{ add(new UnitPart(Units.Pole, 2)); }} - ); - - //--- Volume - put - ( - Units.CubicInch, - new ArrayList() {{ add(new UnitPart(Units.Inch, 3)); }} - ); - - //--- Velocity - put - ( - Units.InchPerSecond, - new ArrayList() - {{ - add(new UnitPart(Units.Inch)); - add(new UnitPart(Units.Second, -1)); - }} - ); - put - ( - Units.Knot, - new ArrayList() - {{ - add(new UnitPart(Units.NauticalMile)); - add(new UnitPart(Units.Hour, -1)); - }} - ); - put - ( - Units.KilometrePerHour, - new ArrayList() - {{ - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Kilo)); - add(new UnitPart(Units.Hour, -1)); - }} - ); - put - ( - Units.MilePerHour, - new ArrayList() - {{ - add(new UnitPart(Units.Mile)); - add(new UnitPart(Units.Hour, -1)); - }} - ); - - //--- Acceleration - put - ( - Units.InchPerSquareSecond, - new ArrayList() - {{ - add(new UnitPart(Units.Inch)); - add(new UnitPart(Units.Second, -2)); - }} - ); - - //--- Energy - put - ( - Units.WattHour, - new ArrayList() - {{ - add(new UnitPart(Units.Metre, 2)); - add(UnitPartInternal.NewUnitPart(Units.Gram, SIPrefixValues.Kilo)); - add(new UnitPart(Units.Hour)); - add(new UnitPart(Units.Second, -3)); - }} - ); - - //--- Pressure - put - ( - Units.TechnicalAtmosphere, - new ArrayList() - {{ - add(new UnitPart(Units.Kilopond)); - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi, -2)); - }} - ); - put - ( - Units.PoundforcePerSquareInch, - new ArrayList() - {{ - add(new UnitPart(Units.PoundForce)); - add(new UnitPart(Units.Inch, -2)); - }} - ); - put - ( - Units.PoundforcePerSquareFoot, - new ArrayList() - {{ - add(new UnitPart(Units.PoundForce)); - add(new UnitPart(Units.Foot, -2)); - }} - ); - put - ( - Units.KipPerSquareInch, - new ArrayList() - {{ - add(new UnitPart(Units.Kip)); - add(new UnitPart(Units.Inch, -2)); - }} - ); - put - ( - Units.Barye, - new ArrayList() - {{ - add(new UnitPart(Units.Dyne)); - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi, -2)); - }} - ); - - //--- Angular velocity - put - ( - Units.RevolutionPerMinute, - new ArrayList() - {{ - add(new UnitPart(Units.Revolution)); - add(new UnitPart(Units.Minute, -1)); - }} - ); - - //--- Solid Angle - put - ( - Units.SquareDegree, - new ArrayList() - {{ - add(new UnitPart(Units.Degree, 2)); - }} - ); - - //--- Electric Charge - put - ( - Units.AmpereHour, - new ArrayList() - {{ - add(new UnitPart(Units.Ampere)); - add(new UnitPart(Units.Hour)); - }} - ); - - //--- Magnetic Field B - put - ( - Units.Gauss, - new ArrayList() - {{ - add(new UnitPart(Units.Maxwell)); - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi, -2)); - }} - ); - - //--- Luminous Energy - put - ( - Units.Talbot, - new ArrayList() - {{ - add(new UnitPart(Units.Lumen)); - add(new UnitPart(Units.Second)); - }} - ); - - //--- Luminance - put - ( - Units.Nit, - new ArrayList() - {{ - add(new UnitPart(Units.Candela)); - add(new UnitPart(Units.Metre, -2)); - }} - ); - - //--- Fuel Economy - put - ( - Units.USCSMilePerGallon, - new ArrayList() - {{ - add(new UnitPart(Units.Mile)); - add(new UnitPart(Units.LiquidGallon, -1)); - }} - ); - put - ( - Units.KilometrePerLitre, - new ArrayList() - {{ - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Kilo)); - add(new UnitPart(Units.Litre, -1)); - }} - ); - } - } - }; - - AllBasicUnits = new HashMap>() - { - { - { - put - ( - UnitTypes.Length, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Metre)); - put(UnitSystems.CGS, new BasicUnit(Units.Metre, SIPrefixValues.Centi)); - put(UnitSystems.Imperial, new BasicUnit(Units.Foot)); - } - } - ); - put - ( - UnitTypes.Area, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.SquareMetre)); - put(UnitSystems.CGS, new BasicUnit(Units.SquareCentimetre)); - put(UnitSystems.Imperial, new BasicUnit(Units.SquareFoot)); - } - } - ); - put - ( - UnitTypes.Volume, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.CubicMetre)); - put(UnitSystems.CGS, new BasicUnit(Units.CubicCentimetre)); - put(UnitSystems.Imperial, new BasicUnit(Units.CubicFoot)); - } - } - ); - put - ( - UnitTypes.Mass, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Gram, SIPrefixValues.Kilo)); - put(UnitSystems.CGS, new BasicUnit(Units.Gram)); - put(UnitSystems.Imperial, new BasicUnit(Units.Pound)); - } - } - ); - put - ( - UnitTypes.Time, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Second)); - put(UnitSystems.CGS, new BasicUnit(Units.Second)); - put(UnitSystems.Imperial, new BasicUnit(Units.Second)); - } - } - ); - put - ( - UnitTypes.Force, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Newton)); - put(UnitSystems.CGS, new BasicUnit(Units.Dyne)); - put(UnitSystems.Imperial, new BasicUnit(Units.PoundForce)); - } - } - ); - put - ( - UnitTypes.Energy, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Joule)); - put(UnitSystems.CGS, new BasicUnit(Units.Erg)); - put(UnitSystems.Imperial, new BasicUnit(Units.BritishThermalUnit)); - } - } - ); - put - ( - UnitTypes.Power, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Watt)); - put(UnitSystems.CGS, new BasicUnit(Units.ErgPerSecond)); - put(UnitSystems.Imperial, new BasicUnit(Units.Horsepower)); - } - } - ); - put - ( - UnitTypes.Temperature, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Kelvin)); - put(UnitSystems.Imperial, new BasicUnit(Units.DegreeFahrenheit)); - put(UnitSystems.CGS, new BasicUnit(Units.Kelvin)); - } - } - ); - put - ( - UnitTypes.Angle, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Radian)); - put(UnitSystems.CGS, new BasicUnit(Units.Radian)); - put(UnitSystems.Imperial, new BasicUnit(Units.Radian)); - } - } - ); - put - ( - UnitTypes.SolidAngle, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Steradian)); - put(UnitSystems.CGS, new BasicUnit(Units.Steradian)); - put(UnitSystems.Imperial, new BasicUnit(Units.Steradian)); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Ampere)); - put(UnitSystems.CGS, new BasicUnit(Units.Ampere)); - put(UnitSystems.Imperial, new BasicUnit(Units.Ampere)); - } - } - ); - put - ( - UnitTypes.LuminousIntensity, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Candela)); - put(UnitSystems.CGS, new BasicUnit(Units.Candela)); - put(UnitSystems.Imperial, new BasicUnit(Units.Candela)); - } - } - ); - put - ( - UnitTypes.AmountOfSubstance, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Mole)); - put(UnitSystems.CGS, new BasicUnit(Units.Mole)); - put(UnitSystems.Imperial, new BasicUnit(Units.Mole)); - } - } - ); - put - ( - UnitTypes.Information, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Bit)); - put(UnitSystems.CGS, new BasicUnit(Units.Bit)); - put(UnitSystems.Imperial, new BasicUnit(Units.Bit)); - } - } - ); - } - } - }; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2f/4090d3fcbc4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2f/4090d3fcbc4a0017160ae291ab4667e2 deleted file mode 100644 index 09bfac2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2f/4090d3fcbc4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2f/90e5599b644c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2f/90e5599b644c0017146ede6da4ae5d42 deleted file mode 100644 index c76abee..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2f/90e5599b644c0017146ede6da4ae5d42 +++ /dev/null @@ -1,437 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - System.out.println("Condition 4 true"); - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - System.out.println("Condition 5 true"); - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2f/d02be9d9c14a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2f/d02be9d9c14a00171634abff01ee97d5 deleted file mode 100644 index 00d2ce9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/2f/d02be9d9c14a00171634abff01ee97d5 +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/30/204064ba2f4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/30/204064ba2f4a001712d4a4f7b050cac8 deleted file mode 100644 index 8b59b4a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/30/204064ba2f4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1864 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result - //result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - //new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - if(unitInfo.Parts.size() == 2) - { - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - } - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/33/501dc0455c4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/33/501dc0455c4c0017146ede6da4ae5d42 deleted file mode 100644 index 82fbbf1..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/33/501dc0455c4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,163 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - System.out.println(UnitPNonUnitInfoAreEqual(first, second)); - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return (first.Error.equals(second.Error)); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type != ErrorTypes.None || secondInfo.Error.Type != ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling == second.ExceptionHandling && - first.Type == second.Type - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/33/c0cbc733614c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/33/c0cbc733614c0017146ede6da4ae5d42 deleted file mode 100644 index f489763..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/33/c0cbc733614c0017146ede6da4ae5d42 +++ /dev/null @@ -1,2636 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; - -import java.util.AbstractMap; -import java.util.HashMap; -import java.util.stream.Collectors; - - -/** -Class containing the main hardcoded resources which are used for internal purposes. -In the original C# code, all this is included in the file Keywords_Private_Main. - **/ -@SuppressWarnings("serial") -public class HCMain -{ - //Main classification for all the units (type, system and conversion factor). - //This dictionary represents an easily-modifiable container of well-structured unit information. - //After using all this information to create more specific/efficient collections, GetAllMain() deletes it. - public static HashMap>> AllUnits; - - /** - HashMap mostly meant to deal with the Imperial/USCS peculiar relationship. - **/ - public static HashMap AllBasicSystems; - - /** - Some times, all what matters is knowing whether the system is metric (SI/CGS) or English (Imperial/USCS). - **/ - public static HashMap AllMetricEnglish; - - /** - This collection relates all the unnamed units with their associated systems. - There are many units which don't fit any Units enum case, the unnamed units. - Unnamed units avoid a huge (and not too logical) hardcoding effort. - Note that UnitParser supports much more units than just the members of the Units enum. - By bearing in mind that any combination of named units forming a supported type is also - supported, the total number of supported units is way too big to even think about facing - it in a hardcoding-all-of-them way. - **/ - public static HashMap DefaultUnnamedUnits; - - /** - Relates all the units with their respective types. - The call to GetALLMain() also populates all the collections below this line. - **/ - public static HashMap AllUnitTypes; - - /**Relates all the units with their respective systems.**/ - public static HashMap AllUnitSystems; - - /**Relates all the units with their respective conversion factors.**/ - public static HashMap AllUnitConversionFactors; - - /**Includes all the supported unit string representations (case doesn't matter).**/ - public static HashMap AllUnitStrings; - - /**Includes secondary symbols for some units (case does matter).**/ - public static HashMap AllUnitSymbols2; - - /**Some conversion factors are too small/big for the decimal type.**/ - public static HashMap AllBeyondDecimalConversionFactors; - - public static String Start() - { - AllUnits = new HashMap>>() - { - { - put - ( - UnitTypes.None, - new HashMap>() - { - { - put - ( - UnitSystems.SI, new HashMap() - { - { put(Units.ValidSIUnit, 1.0); } - } - ); - put - ( - UnitSystems.Imperial, new HashMap() - { - { put(Units.ValidImperialUSCSUnit, 1.0); put(Units.ValidImperialUnit, 1.0); } - } - ); - put - ( - UnitSystems.USCS, new HashMap() - { - { put(Units.ValidUSCSUnit, 1.0); } - } - ); - put - ( - UnitSystems.CGS, new HashMap() - { - { put(Units.ValidCGSUnit, 1.0); } - } - ); - put - ( - UnitSystems.None, new HashMap() - { - { put(Units.ValidUnit, 1.0); put(Units.Unitless, 1.0); } - } - ); - } - } - ); - put - ( - UnitTypes.Length, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Metre, UnitConversionFactors.Metre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Centimetre, UnitConversionFactors.Centimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Foot, UnitConversionFactors.Foot); - put(Units.Thou, UnitConversionFactors.Thou); - put(Units.Mil, UnitConversionFactors.Mil); - put(Units.Inch, UnitConversionFactors.Inch); - put(Units.Yard, UnitConversionFactors.Yard); - put(Units.Fathom, UnitConversionFactors.Fathom); - put(Units.Rod, UnitConversionFactors.Rod); - put(Units.Perch, UnitConversionFactors.Perch); - put(Units.Pole, UnitConversionFactors.Pole); - put(Units.Chain, UnitConversionFactors.Chain); - put(Units.Furlong, UnitConversionFactors.Furlong); - put(Units.Mile, UnitConversionFactors.Mile); - put(Units.Link, UnitConversionFactors.Link); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.SurveyInch, UnitConversionFactors.SurveyInch); - put(Units.SurveyFoot, UnitConversionFactors.SurveyFoot); - put(Units.SurveyYard, UnitConversionFactors.SurveyYard); - put(Units.SurveyRod, UnitConversionFactors.SurveyRod); - put(Units.SurveyChain, UnitConversionFactors.SurveyChain); - put(Units.SurveyLink, UnitConversionFactors.SurveyLink); - put(Units.SurveyMile, UnitConversionFactors.SurveyMile); - put(Units.SurveyFathom, UnitConversionFactors.SurveyFathom); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.AstronomicalUnit, UnitConversionFactors.AstronomicalUnit); - put(Units.NauticalMile, UnitConversionFactors.NauticalMile); - put(Units.Angstrom, UnitConversionFactors.Angstrom); - put(Units.Fermi, UnitConversionFactors.Fermi); - put(Units.LightYear, UnitConversionFactors.LightYear); - put(Units.Parsec, UnitConversionFactors.Parsec); - put(Units.Micron, UnitConversionFactors.Micron); - } - } - ); - } - } - ); - put - ( - UnitTypes.Mass, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Gram, UnitConversionFactors.Gram); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Pound, UnitConversionFactors.Pound); - put(Units.Grain, UnitConversionFactors.Grain); - put(Units.Drachm, UnitConversionFactors.Drachm); - put(Units.Ounce, UnitConversionFactors.Ounce); - put(Units.Stone, UnitConversionFactors.Stone); - put(Units.Slug, UnitConversionFactors.Slug); - put(Units.Quarter, UnitConversionFactors.Quarter); - put(Units.LongQuarter, UnitConversionFactors.LongQuarter); - put(Units.Hundredweight, UnitConversionFactors.Hundredweight); - put(Units.LongHundredweight, UnitConversionFactors.LongHundredweight); - put(Units.Ton, UnitConversionFactors.Ton); - put(Units.LongTon, UnitConversionFactors.LongTon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.ShortQuarter, UnitConversionFactors.ShortQuarter); - put(Units.ShortHundredweight, UnitConversionFactors.ShortHundredweight); - put(Units.ShortTon, UnitConversionFactors.ShortTon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.MetricTon, UnitConversionFactors.MetricTon); - put(Units.Dalton, UnitConversionFactors.Dalton); - put(Units.UnifiedAtomicMassUnit, UnitConversionFactors.UnifiedAtomicMassUnit); - put(Units.Carat, UnitConversionFactors.Carat); - } - } - ); - } - } - ); - put - ( - UnitTypes.Time, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Second, UnitConversionFactors.Second); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Minute, UnitConversionFactors.Minute); - put(Units.Hour, UnitConversionFactors.Hour); - put(Units.Day, UnitConversionFactors.Day); - put(Units.Shake, UnitConversionFactors.Shake); - } - } - ); - } - } - ); - put - ( - UnitTypes.Area, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquareMetre, UnitConversionFactors.SquareMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.SquareCentimetre, UnitConversionFactors.SquareCentimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.SquareFoot, UnitConversionFactors.SquareFoot); - put(Units.SquareInch, UnitConversionFactors.SquareInch); - put(Units.SquareRod, UnitConversionFactors.SquareRod); - put(Units.SquarePerch, UnitConversionFactors.SquarePerch); - put(Units.SquarePole, UnitConversionFactors.SquarePole); - put(Units.Rood, UnitConversionFactors.Rood); - put(Units.Acre, UnitConversionFactors.Acre); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.SurveyAcre, UnitConversionFactors.SurveyAcre); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Are, UnitConversionFactors.Are); - put(Units.Barn, UnitConversionFactors.Barn); - } - } - ); - } - } - ); - put - ( - UnitTypes.Volume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetre, UnitConversionFactors.CubicMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.CubicCentimetre, UnitConversionFactors.CubicCentimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.CubicFoot, UnitConversionFactors.CubicFoot); - put(Units.CubicInch, UnitConversionFactors.CubicInch); - put(Units.FluidOunce, UnitConversionFactors.FluidOunce); - put(Units.ImperialFluidOunce, UnitConversionFactors.ImperialFluidOunce); - put(Units.Gill, UnitConversionFactors.Gill); - put(Units.ImperialGill, UnitConversionFactors.ImperialGill); - put(Units.Pint, UnitConversionFactors.Pint); - put(Units.ImperialPint, UnitConversionFactors.ImperialPint); - put(Units.Quart, UnitConversionFactors.Quart); - put(Units.ImperialQuart, UnitConversionFactors.ImperialQuart); - put(Units.Gallon, UnitConversionFactors.Gallon); - put(Units.ImperialGallon, UnitConversionFactors.ImperialGallon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.USCSFluidOunce, UnitConversionFactors.USCSFluidOunce); - put(Units.USCSGill, UnitConversionFactors.USCSGill); - put(Units.LiquidPint, UnitConversionFactors.LiquidPint); - put(Units.DryPint, UnitConversionFactors.DryPint); - put(Units.LiquidQuart, UnitConversionFactors.LiquidQuart); - put(Units.DryQuart, UnitConversionFactors.DryQuart); - put(Units.LiquidGallon, UnitConversionFactors.LiquidGallon); - put(Units.DryGallon, UnitConversionFactors.DryGallon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Litre, UnitConversionFactors.Litre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Angle, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Radian, UnitConversionFactors.Radian); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Degree, UnitConversionFactors.Degree); - put(Units.Arcminute, UnitConversionFactors.Arcminute); - put(Units.Arcsecond, UnitConversionFactors.Arcsecond); - put(Units.Revolution, UnitConversionFactors.Revolution); - put(Units.Gradian, UnitConversionFactors.Gradian); - put(Units.Gon, UnitConversionFactors.Gon); - } - } - ); - } - } - ); - put - ( - UnitTypes.Information, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bit, UnitConversionFactors.Bit); - put(Units.Byte, UnitConversionFactors.Byte); - put(Units.Nibble, UnitConversionFactors.Nibble); - put(Units.Quartet, UnitConversionFactors.Quartet); - put(Units.Octet, UnitConversionFactors.Octet); - } - } - ); - } - } - ); - put - ( - UnitTypes.Force, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Newton, UnitConversionFactors.Newton); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.PoundForce, UnitConversionFactors.PoundForce); - put(Units.Poundal, UnitConversionFactors.Poundal); - put(Units.OunceForce, UnitConversionFactors.OunceForce); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Dyne, UnitConversionFactors.Dyne); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Kilopond, UnitConversionFactors.Kilopond); - put(Units.Kip, UnitConversionFactors.Kip); - } - } - ); - } - } - ); - put - ( - UnitTypes.Velocity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerSecond, UnitConversionFactors.MetrePerSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.CentimetrePerSecond, UnitConversionFactors.CentimetrePerSecond); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootPerSecond, UnitConversionFactors.FootPerSecond); - put(Units.InchPerSecond, UnitConversionFactors.InchPerSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Knot, UnitConversionFactors.Knot); - put(Units.KilometrePerHour, UnitConversionFactors.KilometrePerHour); - put(Units.MilePerHour, UnitConversionFactors.MilePerHour); - } - } - ); - } - } - ); - put - ( - UnitTypes.Acceleration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerSquareSecond, UnitConversionFactors.MetrePerSquareSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Gal, UnitConversionFactors.Gal); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootPerSquareSecond, UnitConversionFactors.FootPerSquareSecond); - put(Units.InchPerSquareSecond, UnitConversionFactors.InchPerSquareSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.Energy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Joule, UnitConversionFactors.Joule); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.BritishThermalUnit, UnitConversionFactors.BritishThermalUnit); - put(Units.ThermochemicalBritishThermalUnit, UnitConversionFactors.ThermochemicalBritishThermalUnit); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Erg, UnitConversionFactors.Erg); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Electronvolt, UnitConversionFactors.Electronvolt); - put(Units.WattHour, UnitConversionFactors.WattHour); - put(Units.Calorie, UnitConversionFactors.Calorie); - put(Units.ThermochemicalCalorie, UnitConversionFactors.ThermochemicalBritishThermalUnit); - put(Units.FoodCalorie, UnitConversionFactors.FoodCalorie); - put(Units.Therm, UnitConversionFactors.Therm); - put(Units.UKTherm, UnitConversionFactors.UKTherm); - put(Units.USTherm, UnitConversionFactors.USTherm); - } - } - ); - } - } - ); - put - ( - UnitTypes.Power, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Watt, UnitConversionFactors.Watt); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.ErgPerSecond, UnitConversionFactors.ErgPerSecond); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Horsepower, UnitConversionFactors.Horsepower); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.MetricHorsepower, UnitConversionFactors.MetricHorsepower); - put(Units.ElectricHorsepower, UnitConversionFactors.ElectricHorsepower); - put(Units.BoilerHorsepower, UnitConversionFactors.BoilerHorsepower); - put(Units.TonOfRefrigeration, UnitConversionFactors.TonOfRefrigeration); - } - } - ); - } - } - ); - put - ( - UnitTypes.Pressure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Pascal, UnitConversionFactors.Pascal); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Barye, UnitConversionFactors.Barye); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.PoundforcePerSquareInch, UnitConversionFactors.PoundforcePerSquareInch); - put(Units.PoundforcePerSquareFoot, UnitConversionFactors.PoundforcePerSquareFoot); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bar, UnitConversionFactors.Bar); - put(Units.Atmosphere, UnitConversionFactors.Atmosphere); - put(Units.TechnicalAtmosphere, UnitConversionFactors.TechnicalAtmosphere); - put(Units.MillimetreOfMercury, UnitConversionFactors.MillimetreOfMercury); - put(Units.InchOfMercury32F, UnitConversionFactors.InchOfMercury32F); - put(Units.InchOfMercury60F, UnitConversionFactors.InchOfMercury60F); - put(Units.Torr, UnitConversionFactors.Torr); - put(Units.KipPerSquareInch, UnitConversionFactors.KipPerSquareInch); - } - } - ); - } - } - ); - put - ( - UnitTypes.Frequency, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Hertz, UnitConversionFactors.Hertz); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.CyclePerSecond, UnitConversionFactors.CyclePerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCharge, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Coulomb, UnitConversionFactors.Coulomb); - put(Units.AmpereHour, UnitConversionFactors.AmpereHour); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Franklin, UnitConversionFactors.Franklin); - put(Units.Statcoulomb, UnitConversionFactors.Statcoulomb); - put(Units.ESUOfCharge, UnitConversionFactors.ESUOfCharge); - put(Units.Abcoulomb, UnitConversionFactors.Abcoulomb); - put(Units.EMUOfCharge, UnitConversionFactors.EMUOfCharge); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Ampere, UnitConversionFactors.Ampere); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statampere, UnitConversionFactors.Statampere); - put(Units.ESUOfCurrent, UnitConversionFactors.ESUOfCurrent); - put(Units.Abampere, UnitConversionFactors.Abampere); - put(Units.Biot, UnitConversionFactors.Biot); - put(Units.EMUOfCurrent, UnitConversionFactors.EMUOfCurrent); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricVoltage, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Volt, UnitConversionFactors.Volt); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statvolt, UnitConversionFactors.Statvolt); - put(Units.ESUOfElectricPotential, UnitConversionFactors.ESUOfElectricPotential); - put(Units.Abvolt, UnitConversionFactors.Abvolt); - put(Units.EMUOfElectricPotential, UnitConversionFactors.EMUOfElectricPotential); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricResistance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Ohm, UnitConversionFactors.Ohm); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statohm, UnitConversionFactors.Statohm); - put(Units.ESUOfResistance, UnitConversionFactors.ESUOfResistance); - put(Units.Abohm, UnitConversionFactors.Abohm); - put(Units.EMUOfResistance, UnitConversionFactors.EMUOfResistance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricResistivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.OhmMetre, UnitConversionFactors.OhmMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricConductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Siemens, UnitConversionFactors.Siemens); - put(Units.Mho, UnitConversionFactors.Mho); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statmho, UnitConversionFactors.Statmho); - put(Units.Statsiemens, UnitConversionFactors.Statsiemens); - put(Units.Abmho, UnitConversionFactors.Abmho); - put(Units.Absiemens, UnitConversionFactors.Absiemens); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Gemmho, UnitConversionFactors.Gemmho); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricConductivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SiemensPerMetre, UnitConversionFactors.SiemensPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCapacitance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Farad, UnitConversionFactors.Farad); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statfarad, UnitConversionFactors.Statfarad); - put(Units.ESUOfCapacitance, UnitConversionFactors.ESUOfCapacitance); - put(Units.Abfarad, UnitConversionFactors.Abfarad); - put(Units.EMUOfCapacitance, UnitConversionFactors.EMUOfCapacitance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricInductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Henry, UnitConversionFactors.Henry); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stathenry, UnitConversionFactors.Stathenry); - put(Units.ESUOfInductance, UnitConversionFactors.ESUOfInductance); - put(Units.Abhenry, UnitConversionFactors.Abhenry); - put(Units.EMUOfInductance, UnitConversionFactors.EMUOfInductance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricDipoleMoment, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombMetre, UnitConversionFactors.CoulombMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Debye, UnitConversionFactors.Debye); - } - } - ); - } - } - ); - put - ( - UnitTypes.Temperature, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - //Mere Placeholders. Temperature conversions are managed through a function. - put(Units.Kelvin, 1.0); - put(Units.DegreeCelsius, 1.0); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.DegreeFahrenheit, 1.0); - put(Units.DegreeRankine, 1.0); - } - } - ); - } - } - ); - put - ( - UnitTypes.Wavenumber, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.ReciprocalMetre, UnitConversionFactors.ReciprocalMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Kayser, UnitConversionFactors.Kayser); - } - } - ); - } - } - ); - put - ( - UnitTypes.Viscosity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.PascalSecond, UnitConversionFactors.PascalSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Poise, UnitConversionFactors.Poise); - } - } - ); - } - } - ); - put - ( - UnitTypes.KinematicViscosity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquareMetrePerSecond, UnitConversionFactors.SquareMetrePerSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stokes, UnitConversionFactors.Stokes); - } - } - ); - } - } - ); - put - ( - UnitTypes.AmountOfSubstance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Mole, UnitConversionFactors.Mole); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.PoundMole, UnitConversionFactors.PoundMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.Momentum, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonSecond, UnitConversionFactors.NewtonSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularVelocity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.RadianPerSecond, UnitConversionFactors.RadianPerSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.RevolutionPerMinute, UnitConversionFactors.RevolutionPerMinute); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularAcceleration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.RadianPerSquareSecond, UnitConversionFactors.RadianPerSquareSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularMomentum, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JouleSecond, UnitConversionFactors.JouleSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.MomentOfInertia, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramSquareMetre, UnitConversionFactors.KilogramSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SolidAngle, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Steradian, UnitConversionFactors.Steradian); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.SquareDegree, UnitConversionFactors.SquareDegree); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousIntensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Candela, UnitConversionFactors.Candela); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousFlux, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Lumen, UnitConversionFactors.Lumen); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousEnergy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.LumenSecond, UnitConversionFactors.LumenSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Talbot, UnitConversionFactors.Talbot); - } - } - ); - } - } - ); - put - ( - UnitTypes.Luminance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CandelaPerSquareMetre, UnitConversionFactors.CandelaPerSquareMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stilb, UnitConversionFactors.Stilb); - put(Units.Lambert, UnitConversionFactors.Lambert); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootLambert, UnitConversionFactors.FootLambert); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Nit, UnitConversionFactors.Nit); - } - } - ); - } - } - ); - put - ( - UnitTypes.Illuminance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Lux, UnitConversionFactors.Lux); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootCandle, UnitConversionFactors.FootCandle); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Phot, UnitConversionFactors.Phot); - } - } - ); - } - } - ); - put - ( - UnitTypes.Logarithmic, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bel, UnitConversionFactors.Bel); - put(Units.Neper, UnitConversionFactors.Neper); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFlux, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Weber, UnitConversionFactors.Weber); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Maxwell, UnitConversionFactors.Maxwell); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFieldB, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Tesla, UnitConversionFactors.Tesla); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Gauss, UnitConversionFactors.Gauss); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFieldH, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.AmperePerMetre, UnitConversionFactors.AmperePerMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Oersted, UnitConversionFactors.Oersted); - } - } - ); - } - } - ); - put - ( - UnitTypes.Radioactivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Becquerel, UnitConversionFactors.Becquerel); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Curie, UnitConversionFactors.Curie); - put(Units.DisintegrationsPerMinute, UnitConversionFactors.DisintegrationsPerMinute); - put(Units.DisintegrationsPerSecond, UnitConversionFactors.DisintegrationsPerSecond); - put(Units.Rutherford, UnitConversionFactors.Rutherford); - } - } - ); - } - } - ); - put - ( - UnitTypes.AbsorbedDose, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Gray, UnitConversionFactors.Gray); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Rad, UnitConversionFactors.Rad); - } - } - ); - } - } - ); - put - ( - UnitTypes.AbsorbedDoseRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.GrayPerSecond, UnitConversionFactors.GrayPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.EquivalentDose, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Sievert, UnitConversionFactors.Sievert); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.REM, UnitConversionFactors.REM); - } - } - ); - } - } - ); - put - ( - UnitTypes.Exposure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerKilogram, UnitConversionFactors.CoulombPerKilogram); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Roentgen, UnitConversionFactors.Roentgen); - } - } - ); - } - } - ); - put - ( - UnitTypes.CatalyticActivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Katal, UnitConversionFactors.Katal); - } - } - ); - } - } - ); - put - ( - UnitTypes.CatalyticActivityConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KatalPerCubicMetre, UnitConversionFactors.KatalPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Jerk, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerCubicSecond, UnitConversionFactors.MetrePerCubicSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.MassFlowRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerSecond, UnitConversionFactors.KilogramPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.Density, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerCubicMetre, UnitConversionFactors.KilogramPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.AreaDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerSquareMetre, UnitConversionFactors.KilogramPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.EnergyDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerCubicMetre, UnitConversionFactors.JoulePerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SpecificVolume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerKilogram, UnitConversionFactors.CubicMetrePerKilogram); - } - } - ); - } - } - ); - put - ( - UnitTypes.VolumetricFlowRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerSecond, UnitConversionFactors.CubicMetrePerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SurfaceTension, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerSquareMetre, UnitConversionFactors.JoulePerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SpecificWeight, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonPerCubicMetre, UnitConversionFactors.NewtonPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalConductivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerMetrePerKelvin, UnitConversionFactors.WattPerMetrePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalConductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerKelvin, UnitConversionFactors.WattPerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalResistivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetreKelvinPerWatt, UnitConversionFactors.MetreKelvinPerWatt); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalResistance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KelvinPerWatt, UnitConversionFactors.KelvinPerWatt); - } - } - ); - } - } - ); - put - ( - UnitTypes.HeatTransferCoefficient, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSquareMetrePerKelvin, UnitConversionFactors.WattPerSquareMetrePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.HeatFluxDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSquareMetre, UnitConversionFactors.WattPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Entropy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerKelvin, UnitConversionFactors.JoulePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricFieldStrength, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonPerCoulomb, UnitConversionFactors.NewtonPerCoulomb); - put(Units.VoltPerMetre, UnitConversionFactors.VoltPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.LinearElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerMetre, UnitConversionFactors.CoulombPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerSquareMetre, UnitConversionFactors.CoulombPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerCubicMetre, UnitConversionFactors.CoulombPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.CurrentDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.AmperePerSquareMetre, UnitConversionFactors.AmperePerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermittivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.FaradPerMetre, UnitConversionFactors.FaradPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermeability, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.HenryPerMetre, UnitConversionFactors.HenryPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarEnergy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerMole, UnitConversionFactors.JoulePerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarEntropy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerMolePerKelvin, UnitConversionFactors.JoulePerMolePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarVolume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerMole, UnitConversionFactors.CubicMetrePerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarMass, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerMole, UnitConversionFactors.KilogramPerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MolePerCubicMetre, UnitConversionFactors.MolePerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolalConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MolePerKilogram, UnitConversionFactors.MolePerKilogram); - } - } - ); - } - } - ); - put - ( - UnitTypes.RadiantIntensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSteradian, UnitConversionFactors.WattPerSteradian); - } - } - ); - } - } - ); - put - ( - UnitTypes.Radiance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSteradianPerSquareMetre, UnitConversionFactors.WattPerSteradianPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.FuelEconomy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.InverseSquareMetre, UnitConversionFactors.InverseSquareMetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.MilePerGallon, UnitConversionFactors.MilePerGallon); - put(Units.ImperialMilePerGallon, UnitConversionFactors.ImperialMilePerGallon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.USCSMilePerGallon, UnitConversionFactors.USCSMilePerGallon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.KilometrePerLitre, UnitConversionFactors.KilometrePerLitre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SoundExposure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquarePascalSecond, UnitConversionFactors.SquarePascalSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SoundImpedance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.PascalSecondPerCubicMetre, UnitConversionFactors.PascalSecondPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.RotationalStiffness, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonMetrePerRadian, UnitConversionFactors.NewtonMetrePerRadian); - } - } - ); - } - } - ); - put - ( - UnitTypes.BitRate, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.BitPerSecond, UnitConversionFactors.BitPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SymbolRate, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Baud, UnitConversionFactors.Baud); - } - } - ); - } - } - ); - } - }; - - AllBasicSystems = new HashMap() - { - { put(UnitSystems.SI, UnitSystems.SI); } - { put(UnitSystems.CGS, UnitSystems.CGS); } - { put(UnitSystems.Imperial, UnitSystems.Imperial); } - { put(UnitSystems.USCS, UnitSystems.Imperial); } - { put(UnitSystems.ImperialAndUSCS, UnitSystems.Imperial); } - { put(UnitSystems.None, UnitSystems.None); } - }; - - AllMetricEnglish = new HashMap() - { - { put(UnitSystems.SI, UnitSystems.SI); } - { put(UnitSystems.CGS, UnitSystems.SI); } - { put(UnitSystems.Imperial, UnitSystems.Imperial); } - { put(UnitSystems.USCS, UnitSystems.Imperial); } - { put(UnitSystems.ImperialAndUSCS, UnitSystems.Imperial); } - { put(UnitSystems.None, UnitSystems.None); } - }; - - DefaultUnnamedUnits = (HashMap)AllUnits.get(UnitTypes.None).entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - x.getValue(), new AbstractMap.SimpleEntry(Units.None, 0.0) - ) - .getKey() - ) - ); - - AllUnitTypes = MethodsHardcoding.GetAllMain(); - - return ""; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/6042e2aeb14a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/6042e2aeb14a00171059ebc16969059f deleted file mode 100644 index adf50fc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/6042e2aeb14a00171059ebc16969059f +++ /dev/null @@ -1,1059 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - UnitInfo test22 = Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - System.out.println(original.Value); - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/c08a4be4294a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/c08a4be4294a001712d4a4f7b050cac8 deleted file mode 100644 index 9d482f3..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/c08a4be4294a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - System.out.println(parseInfo.UnitInfo.Parts.get(1).Unit); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/e057ca40934a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/e057ca40934a00171930ee4d171ed0de deleted file mode 100644 index fbe86b5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/e057ca40934a00171930ee4d171ed0de +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - System.out.println(big2.Value + " " + big2.BaseTenExponent + " " + big2.Prefix.Factor); - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/f0b48076b24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/f0b48076b24a00171059ebc16969059f deleted file mode 100644 index 391f7f7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/35/f0b48076b24a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/36/b04ecf14294c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/36/b04ecf14294c00171ae7fcf2c321c986 deleted file mode 100644 index 1475cc2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/36/b04ecf14294c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1052 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/36/b0f21d497a4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/36/b0f21d497a4c00171945f16efe0d9b5d deleted file mode 100644 index dbb7e3c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/36/b0f21d497a4c00171945f16efe0d9b5d +++ /dev/null @@ -1,2558 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import InternalUnitParser.Classes.*; -import UnitParser.*; - -import java.util.HashMap; -import java.util.ArrayList; - - -@SuppressWarnings("serial") -public class HCCompounds -{ - //Contains the definitions of all the supported compounds, understood as units formed by other units - //and/or variations (e.g., exponents different than 1) of them. - //In order to be as efficient as possible, AllCompounds ignores the difference between dividable and - //non-dividable units. For example: N is formed by kg*m/s2, exactly what this collection expects; on the - //other hand, lbf isn't formed by the expected lb*ft/s2. In any case, note that this "faulty" format is - //only used internally, never shown to the user. - //NOTE: the order of the compounds within each type does matter. The first position is reserved for the main - //fully-expanded version (e.g., mass*length/time2 for force). In the second position, the compound basic - //units (e.g., force) are expected to have their 1-part version (e.g., 1 force part for force). - public static HashMap> AllCompounds; - - //Contains all the named compounds defined by the basic units for the given type/system. - //For example, Newton is formed by kg*m/s^2, the basic mass*length/time units in SI, and that's why it belongs here. - public static HashMap> AllBasicCompounds; - - //Roughly speaking, AllNonBasicCompounds is a container of somehow exceptional situations. - //Some of these units (e.g., centimetre) shouldn't be matched when looking for valid compounds. - public static ArrayList NonBasicCompoundsToSkip; - - //Contains the definition (i.e., UnitPart[] containing their defining units) of all the supported named - //compounds except the ones defined by the corresponding basic units (included in AllBasicCompounds). - public static HashMap> AllNonBasicCompounds; - - //Classifies all the basic units on account of their types and systems. - //Note that these units don't meet the most intuitive interpretation of the basic unit idea. - //That is, they aren't just the most basic constituent of compounds (i.e., impossible to be - //further divided), but also compounds. The reason for this a-priori abnormal configuration - //is that they aren't just used to model SI/CGS compounds, but also Imperial/USCS ones. - //For example: the SI force unit (N) can be defined on account of properly-speaking basic units, - //but the Imperial/USCS version (lbf) cannot. - public static HashMap> AllBasicUnits; - - public static void Start() - { - AllCompounds = new HashMap>() - { - { - { - put - ( - UnitTypes.Area, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Length, 2)); }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Area)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Volume, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Length, 3)); }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Volume)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Velocity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Acceleration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Force, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Force)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Energy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Energy)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Power, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Power)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Pressure, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -1)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Frequency, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Time, -1)); }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricCharge, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricVoltage, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricResistance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricResistivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricConductance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricConductivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricCapacitance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 4)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricInductance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricDipoleMoment, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time, 1)); - add(new CompoundPart(UnitTypes.Length, 1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Wavenumber, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() {{ add(new CompoundPart(UnitTypes.Length, -1)); }} - ) - ); - }} - ); - put - ( - UnitTypes.Viscosity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -1)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.KinematicViscosity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Momentum, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AngularVelocity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Angle)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AngularAcceleration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Angle)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AngularMomentum, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MomentOfInertia, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SolidAngle, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Angle, 2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.LuminousFlux, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.SolidAngle)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.LuminousEnergy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.SolidAngle)); - add(new CompoundPart(UnitTypes.Time)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Luminance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Illuminance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.LuminousIntensity)); - add(new CompoundPart(UnitTypes.SolidAngle)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MagneticFlux, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MagneticFieldB, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MagneticFieldH, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Length, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AbsorbedDose, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AbsorbedDoseRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.EquivalentDose, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Exposure, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Mass, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.CatalyticActivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.CatalyticActivityConcentration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Time, -1)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Jerk, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MassFlowRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Density, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.AreaDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.EnergyDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -1)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SpecificVolume, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.Mass, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.VolumetricFlowRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SurfaceTension, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SpecificWeight, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalConductivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalConductance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalResistivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Temperature)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ThermalResistance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Time, 3)); - add(new CompoundPart(UnitTypes.Temperature)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.HeatTransferCoefficient, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.HeatFluxDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Entropy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectricFieldStrength, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.LinearElectricChargeDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Length, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Time)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.CurrentDensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent)); - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectromagneticPermittivity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.ElectricCurrent, 2)); - add(new CompoundPart(UnitTypes.Time, 4)); - add(new CompoundPart(UnitTypes.Mass, -1)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.ElectromagneticPermeability, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 1)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.ElectricCurrent, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarEnergy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarEntropy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - add(new CompoundPart(UnitTypes.Temperature, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarVolume, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, 3)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarMass, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.AmountOfSubstance, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolarConcentration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Length, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.MolalConcentration, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.AmountOfSubstance)); - add(new CompoundPart(UnitTypes.Mass, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.RadiantIntensity, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.SolidAngle, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.Radiance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Time, -3)); - add(new CompoundPart(UnitTypes.SolidAngle, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.FuelEconomy, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Length, -2)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SoundExposure, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass, 2)); - add(new CompoundPart(UnitTypes.Length, -2)); - add(new CompoundPart(UnitTypes.Time, -3)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.SoundImpedance, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, -4)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.RotationalStiffness, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Mass)); - add(new CompoundPart(UnitTypes.Length, 2)); - add(new CompoundPart(UnitTypes.Time, -2)); - add(new CompoundPart(UnitTypes.Angle, -1)); - }} - ) - ); - }} - ); - put - ( - UnitTypes.BitRate, new ArrayList() - {{ - add - ( - new Compound - ( - new ArrayList() - {{ - add(new CompoundPart(UnitTypes.Information)); - add(new CompoundPart(UnitTypes.Time, -1)); - }} - ) - ); - }} - ); - } - } - }; - - AllBasicCompounds = new HashMap>() - { - { - { - put - ( - UnitTypes.Area, new HashMap() - { - { - put(UnitSystems.SI, Units.SquareMetre); - put(UnitSystems.CGS, Units.SquareCentimetre); - put(UnitSystems.Imperial, Units.SquareFoot); - } - } - ); - put - ( - UnitTypes.Volume, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetre); - put(UnitSystems.CGS, Units.CubicCentimetre); - put(UnitSystems.Imperial, Units.CubicFoot); - } - } - ); - put - ( - UnitTypes.Velocity, new HashMap() - { - { - put(UnitSystems.SI, Units.MetrePerSecond); - put(UnitSystems.CGS, Units.CentimetrePerSecond); - put(UnitSystems.Imperial, Units.FootPerSecond); - } - } - ); - put - ( - UnitTypes.Acceleration, new HashMap() - { - { - put(UnitSystems.SI, Units.MetrePerSquareSecond); - put(UnitSystems.CGS, Units.Gal); - put(UnitSystems.Imperial, Units.FootPerSquareSecond); - } - } - ); - put - ( - UnitTypes.Force, new HashMap() - { - { - put(UnitSystems.SI, Units.Newton); - put(UnitSystems.CGS, Units.Dyne); - put(UnitSystems.Imperial, Units.Poundal); - } - } - ); - put - ( - UnitTypes.Energy, new HashMap() - { - { - put(UnitSystems.SI, Units.Joule); - put(UnitSystems.CGS, Units.Erg); - } - } - ); - put - ( - UnitTypes.Power, new HashMap() - { - { - put(UnitSystems.SI, Units.Watt); - put(UnitSystems.CGS, Units.ErgPerSecond); - } - } - ); - put - ( - UnitTypes.Pressure, new HashMap() - { - { - put(UnitSystems.SI, Units.Pascal); - put(UnitSystems.CGS, Units.Barye); - put(UnitSystems.Imperial, Units.PoundforcePerSquareFoot); - } - } - ); - put - ( - UnitTypes.Frequency, new HashMap() - { - { - put(UnitSystems.SI, Units.Hertz); - } - } - ); - put - ( - UnitTypes.ElectricCharge, new HashMap() - { - { - put(UnitSystems.SI, Units.Coulomb); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, new HashMap() - { - { - put(UnitSystems.SI, Units.Ampere); - } - } - ); - put - ( - UnitTypes.ElectricVoltage, new HashMap() - { - { - put(UnitSystems.SI, Units.Volt); - } - } - ); - put - ( - UnitTypes.ElectricResistance, new HashMap() - { - { - put(UnitSystems.SI, Units.Ohm); - } - } - ); - put - ( - UnitTypes.ElectricResistivity, new HashMap() - { - { - put(UnitSystems.SI, Units.OhmMetre); - } - } - ); - put - ( - UnitTypes.ElectricConductance, new HashMap() - { - { - put(UnitSystems.SI, Units.Siemens); - } - } - ); - put - ( - UnitTypes.ElectricConductivity, new HashMap() - { - { - put(UnitSystems.SI, Units.SiemensPerMetre); - } - } - ); - put - ( - UnitTypes.ElectricCapacitance, new HashMap() - { - { - put(UnitSystems.SI, Units.Farad); - } - } - ); - put - ( - UnitTypes.ElectricInductance, new HashMap() - { - { - put(UnitSystems.SI, Units.Henry); - } - } - ); - put - ( - UnitTypes.ElectricDipoleMoment, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombMetre); - } - } - ); - put - ( - UnitTypes.Wavenumber, new HashMap() - { - { - put(UnitSystems.SI, Units.ReciprocalMetre); - put(UnitSystems.CGS, Units.Kayser); - } - } - ); - put - ( - UnitTypes.Viscosity, new HashMap() - { - { - put(UnitSystems.SI, Units.PascalSecond); - put(UnitSystems.CGS, Units.Poise); - } - } - ); - put - ( - UnitTypes.KinematicViscosity, new HashMap() - { - { - put(UnitSystems.SI, Units.SquareMetrePerSecond); - put(UnitSystems.CGS, Units.Stokes); - } - } - ); - put - ( - UnitTypes.Momentum, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonSecond); - } - } - ); - put - ( - UnitTypes.AngularVelocity, new HashMap() - { - { - put(UnitSystems.SI, Units.RadianPerSecond); - } - } - ); - put - ( - UnitTypes.AngularAcceleration, new HashMap() - { - { - put(UnitSystems.SI, Units.RadianPerSquareSecond); - } - } - ); - put - ( - UnitTypes.AngularMomentum, new HashMap() - { - { - put(UnitSystems.SI, Units.JouleSecond); - } - } - ); - put - ( - UnitTypes.MomentOfInertia, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramSquareMetre); - } - } - ); - put - ( - UnitTypes.SolidAngle, new HashMap() - { - { - put(UnitSystems.SI, Units.Steradian); - } - } - ); - put - ( - UnitTypes.LuminousFlux, new HashMap() - { - { - put(UnitSystems.SI, Units.Lumen); - } - } - ); - put - ( - UnitTypes.LuminousEnergy, new HashMap() - { - { - put(UnitSystems.SI, Units.LumenSecond); - } - } - ); - put - ( - UnitTypes.Luminance, new HashMap() - { - { - put(UnitSystems.SI, Units.CandelaPerSquareMetre); - put(UnitSystems.CGS, Units.Stilb); - } - } - ); - put - ( - UnitTypes.Illuminance, new HashMap() - { - { - put(UnitSystems.SI, Units.Lux); - put(UnitSystems.CGS, Units.Phot); - put(UnitSystems.Imperial, Units.FootCandle); - } - } - ); - put - ( - UnitTypes.MagneticFlux, new HashMap() - { - { - put(UnitSystems.SI, Units.Weber); - } - } - ); - put - ( - UnitTypes.MagneticFieldB, new HashMap() - { - { - put(UnitSystems.SI, Units.Tesla); - } - } - ); - put - ( - UnitTypes.AbsorbedDose, new HashMap() - { - { - put(UnitSystems.SI, Units.Gray); - } - } - ); - put - ( - UnitTypes.AbsorbedDoseRate, new HashMap() - { - { - put(UnitSystems.SI, Units.GrayPerSecond); - } - } - ); - put - ( - UnitTypes.EquivalentDose, new HashMap() - { - { - put(UnitSystems.SI, Units.Sievert); - } - } - ); - put - ( - UnitTypes.Exposure, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerKilogram); - put(UnitSystems.CGS, Units.Roentgen); - } - } - ); - put - ( - UnitTypes.CatalyticActivity, new HashMap() - { - { - put(UnitSystems.SI, Units.Katal); - } - } - ); - put - ( - UnitTypes.CatalyticActivityConcentration, new HashMap() - { - { - put(UnitSystems.SI, Units.KatalPerCubicMetre); - } - } - ); - put - ( - UnitTypes.Jerk, new HashMap() - { - { - put(UnitSystems.SI, Units.MetrePerCubicSecond); - } - } - ); - put - ( - UnitTypes.MassFlowRate, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerSecond); - } - } - ); - put - ( - UnitTypes.Density, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerCubicMetre); - } - } - ); - put - ( - UnitTypes.AreaDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerSquareMetre); - } - } - ); - put - ( - UnitTypes.EnergyDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerCubicMetre); - } - } - ); - put - ( - UnitTypes.SpecificVolume, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetrePerKilogram); - } - } - ); - put - ( - UnitTypes.VolumetricFlowRate, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetrePerSecond); - } - } - ); - put - ( - UnitTypes.SurfaceTension, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerSquareMetre); - } - } - ); - put - ( - UnitTypes.SpecificWeight, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonPerCubicMetre); - } - } - ); - put - ( - UnitTypes.ThermalConductivity, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerMetrePerKelvin); - } - } - ); - put - ( - UnitTypes.ThermalConductance, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerKelvin); - } - } - ); - put - ( - UnitTypes.ThermalResistivity, new HashMap() - { - { - put(UnitSystems.SI, Units.MetreKelvinPerWatt); - } - } - ); - put - ( - UnitTypes.ThermalResistance, new HashMap() - { - { - put(UnitSystems.SI, Units.KelvinPerWatt); - } - } - ); - put - ( - UnitTypes.HeatTransferCoefficient, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSquareMetrePerKelvin); - } - } - ); - put - ( - UnitTypes.HeatFluxDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSquareMetre); - } - } - ); - put - ( - UnitTypes.Entropy, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerKelvin); - } - } - ); - put - ( - UnitTypes.ElectricFieldStrength, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonPerCoulomb); - } - } - ); - put - ( - UnitTypes.LinearElectricChargeDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerMetre); - } - } - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerSquareMetre); - } - } - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.CoulombPerCubicMetre); - } - } - ); - put - ( - UnitTypes.CurrentDensity, new HashMap() - { - { - put(UnitSystems.SI, Units.AmperePerSquareMetre); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermittivity, new HashMap() - { - { - put(UnitSystems.SI, Units.FaradPerMetre); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermeability, new HashMap() - { - { - put(UnitSystems.SI, Units.HenryPerMetre); - } - } - ); - put - ( - UnitTypes.MolarEnergy, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerMole); - } - } - ); - put - ( - UnitTypes.MolarEntropy, new HashMap() - { - { - put(UnitSystems.SI, Units.JoulePerMolePerKelvin); - } - } - ); - put - ( - UnitTypes.MolarVolume, new HashMap() - { - { - put(UnitSystems.SI, Units.CubicMetrePerMole); - } - } - ); - put - ( - UnitTypes.MolarMass, new HashMap() - { - { - put(UnitSystems.SI, Units.KilogramPerMole); - } - } - ); - put - ( - UnitTypes.MolarConcentration, new HashMap() - { - { - put(UnitSystems.SI, Units.MolePerCubicMetre); - } - } - ); - put - ( - UnitTypes.MolalConcentration, new HashMap() - { - { - put(UnitSystems.SI, Units.MolePerKilogram); - } - } - ); - put - ( - UnitTypes.RadiantIntensity, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSteradian); - } - } - ); - put - ( - UnitTypes.Radiance, new HashMap() - { - { - put(UnitSystems.SI, Units.WattPerSteradianPerSquareMetre); - } - } - ); - put - ( - UnitTypes.FuelEconomy, new HashMap() - { - { - put(UnitSystems.SI, Units.InverseSquareMetre); - put(UnitSystems.Imperial, Units.MilePerGallon); - } - } - ); - put - ( - UnitTypes.SoundExposure, new HashMap() - { - { - put(UnitSystems.SI, Units.SquarePascalSecond); - } - } - ); - put - ( - UnitTypes.SoundImpedance, new HashMap() - { - { - put(UnitSystems.SI, Units.PascalSecondPerCubicMetre); - } - } - ); - put - ( - UnitTypes.RotationalStiffness, new HashMap() - { - { - put(UnitSystems.SI, Units.NewtonMetrePerRadian); - } - } - ); - put - ( - UnitTypes.BitRate, new HashMap() - { - { - put(UnitSystems.SI, Units.BitPerSecond); - put(UnitSystems.Imperial, Units.BitPerSecond); - put(UnitSystems.CGS, Units.BitPerSecond); - } - } - ); - } - } - }; - - NonBasicCompoundsToSkip = new ArrayList() - {{ - add(Units.Centimetre); - }}; - - AllNonBasicCompounds = new HashMap>() - { - { - { - //--- Length - put - ( - Units.Centimetre, //Not exactly a compound, but included here for consistency reasons. - new ArrayList() {{ add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi)); }} - ); - - //--- Area - put - ( - Units.SquareInch, - new ArrayList() {{ add(new UnitPart(Units.Inch, 2)); }} - ); - put - ( - Units.SquareRod, - new ArrayList() {{ add(new UnitPart(Units.Rod, 2)); }} - ); - put - ( - Units.SquarePerch, - new ArrayList() {{ add(new UnitPart(Units.Perch, 2)); }} - ); - put - ( - Units.SquarePole, - new ArrayList() {{ add(new UnitPart(Units.Pole, 2)); }} - ); - - //--- Volume - put - ( - Units.CubicInch, - new ArrayList() {{ add(new UnitPart(Units.Inch, 3)); }} - ); - - //--- Velocity - put - ( - Units.InchPerSecond, - new ArrayList() - {{ - add(new UnitPart(Units.Inch)); - add(new UnitPart(Units.Second, -1)); - }} - ); - put - ( - Units.Knot, - new ArrayList() - {{ - add(new UnitPart(Units.NauticalMile)); - add(new UnitPart(Units.Hour, -1)); - }} - ); - put - ( - Units.KilometrePerHour, - new ArrayList() - {{ - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Kilo)); - add(new UnitPart(Units.Hour, -1)); - }} - ); - put - ( - Units.MilePerHour, - new ArrayList() - {{ - add(new UnitPart(Units.Mile)); - add(new UnitPart(Units.Hour, -1)); - }} - ); - - //--- Acceleration - put - ( - Units.InchPerSquareSecond, - new ArrayList() - {{ - add(new UnitPart(Units.Inch)); - add(new UnitPart(Units.Second, -2)); - }} - ); - - //--- Energy - put - ( - Units.WattHour, - new ArrayList() - {{ - add(new UnitPart(Units.Metre, 2)); - add(UnitPartInternal.NewUnitPart(Units.Gram, SIPrefixValues.Kilo)); - add(new UnitPart(Units.Hour)); - add(new UnitPart(Units.Second, -3)); - }} - ); - - //--- Pressure - put - ( - Units.TechnicalAtmosphere, - new ArrayList() - {{ - add(new UnitPart(Units.Kilopond)); - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi, -2)); - }} - ); - put - ( - Units.PoundforcePerSquareInch, - new ArrayList() - {{ - add(new UnitPart(Units.PoundForce)); - add(new UnitPart(Units.Inch, -2)); - }} - ); - put - ( - Units.PoundforcePerSquareFoot, - new ArrayList() - {{ - add(new UnitPart(Units.PoundForce)); - add(new UnitPart(Units.Foot, -2)); - }} - ); - put - ( - Units.KipPerSquareInch, - new ArrayList() - {{ - add(new UnitPart(Units.Kip)); - add(new UnitPart(Units.Inch, -2)); - }} - ); - put - ( - Units.Barye, - new ArrayList() - {{ - add(new UnitPart(Units.Dyne)); - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi, -2)); - }} - ); - - //--- Angular velocity - put - ( - Units.RevolutionPerMinute, - new ArrayList() - {{ - add(new UnitPart(Units.Revolution)); - add(new UnitPart(Units.Minute, -1)); - }} - ); - - //--- Solid Angle - put - ( - Units.SquareDegree, - new ArrayList() - {{ - add(new UnitPart(Units.Degree, 2)); - }} - ); - - //--- Electric Charge - put - ( - Units.AmpereHour, - new ArrayList() - {{ - add(new UnitPart(Units.Ampere)); - add(new UnitPart(Units.Hour)); - }} - ); - - //--- Magnetic Field B - put - ( - Units.Gauss, - new ArrayList() - {{ - add(new UnitPart(Units.Maxwell)); - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Centi, -2)); - }} - ); - - //--- Luminous Energy - put - ( - Units.Talbot, - new ArrayList() - {{ - add(new UnitPart(Units.Lumen)); - add(new UnitPart(Units.Second)); - }} - ); - - //--- Luminance - put - ( - Units.Nit, - new ArrayList() - {{ - add(new UnitPart(Units.Candela)); - add(new UnitPart(Units.Metre, -2)); - }} - ); - - //--- Fuel Economy - put - ( - Units.USCSMilePerGallon, - new ArrayList() - {{ - add(new UnitPart(Units.Mile)); - add(new UnitPart(Units.LiquidGallon, -1)); - }} - ); - put - ( - Units.KilometrePerLitre, - new ArrayList() - {{ - add(UnitPartInternal.NewUnitPart(Units.Metre, SIPrefixValues.Kilo)); - add(new UnitPart(Units.Litre, -1)); - }} - ); - } - } - }; - - AllBasicUnits = new HashMap>() - { - { - { - put - ( - UnitTypes.Length, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Metre)); - put(UnitSystems.CGS, new BasicUnit(Units.Metre, SIPrefixValues.Centi)); - put(UnitSystems.Imperial, new BasicUnit(Units.Foot)); - } - } - ); - put - ( - UnitTypes.Area, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.SquareMetre)); - put(UnitSystems.CGS, new BasicUnit(Units.SquareCentimetre)); - put(UnitSystems.Imperial, new BasicUnit(Units.SquareFoot)); - } - } - ); - put - ( - UnitTypes.Volume, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.CubicMetre)); - put(UnitSystems.CGS, new BasicUnit(Units.CubicCentimetre)); - put(UnitSystems.Imperial, new BasicUnit(Units.CubicFoot)); - } - } - ); - put - ( - UnitTypes.Mass, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Gram, SIPrefixValues.Kilo)); - put(UnitSystems.CGS, new BasicUnit(Units.Gram)); - put(UnitSystems.Imperial, new BasicUnit(Units.Pound)); - } - } - ); - put - ( - UnitTypes.Time, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Second)); - put(UnitSystems.CGS, new BasicUnit(Units.Second)); - put(UnitSystems.Imperial, new BasicUnit(Units.Second)); - } - } - ); - put - ( - UnitTypes.Force, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Newton)); - put(UnitSystems.CGS, new BasicUnit(Units.Dyne)); - put(UnitSystems.Imperial, new BasicUnit(Units.PoundForce)); - } - } - ); - put - ( - UnitTypes.Energy, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Joule)); - put(UnitSystems.CGS, new BasicUnit(Units.Erg)); - put(UnitSystems.Imperial, new BasicUnit(Units.BritishThermalUnit)); - } - } - ); - put - ( - UnitTypes.Power, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Watt)); - put(UnitSystems.CGS, new BasicUnit(Units.ErgPerSecond)); - put(UnitSystems.Imperial, new BasicUnit(Units.Horsepower)); - } - } - ); - put - ( - UnitTypes.Temperature, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Kelvin)); - put(UnitSystems.Imperial, new BasicUnit(Units.DegreeFahrenheit)); - put(UnitSystems.CGS, new BasicUnit(Units.Kelvin)); - } - } - ); - put - ( - UnitTypes.Angle, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Radian)); - put(UnitSystems.CGS, new BasicUnit(Units.Radian)); - put(UnitSystems.Imperial, new BasicUnit(Units.Radian)); - } - } - ); - put - ( - UnitTypes.SolidAngle, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Steradian)); - put(UnitSystems.CGS, new BasicUnit(Units.Steradian)); - put(UnitSystems.Imperial, new BasicUnit(Units.Steradian)); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Ampere)); - put(UnitSystems.CGS, new BasicUnit(Units.Ampere)); - put(UnitSystems.Imperial, new BasicUnit(Units.Ampere)); - } - } - ); - put - ( - UnitTypes.LuminousIntensity, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Candela)); - put(UnitSystems.CGS, new BasicUnit(Units.Candela)); - put(UnitSystems.Imperial, new BasicUnit(Units.Candela)); - } - } - ); - put - ( - UnitTypes.AmountOfSubstance, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Mole)); - put(UnitSystems.CGS, new BasicUnit(Units.Mole)); - put(UnitSystems.Imperial, new BasicUnit(Units.Mole)); - } - } - ); - put - ( - UnitTypes.Information, new HashMap() - { - { - put(UnitSystems.SI, new BasicUnit(Units.Bit)); - put(UnitSystems.CGS, new BasicUnit(Units.Bit)); - put(UnitSystems.Imperial, new BasicUnit(Units.Bit)); - } - } - ); - } - } - }; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/37/005ea2ca2c4c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/37/005ea2ca2c4c00171ae7fcf2c321c986 deleted file mode 100644 index 78ed627..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/37/005ea2ca2c4c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1052 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = (int)Math.signum(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/37/20ff3720964a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/37/20ff3720964a00171930ee4d171ed0de deleted file mode 100644 index 962c109..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/37/20ff3720964a00171930ee4d171ed0de +++ /dev/null @@ -1,577 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - //unitInfos2.get(bigSmallI[0]).Value = big2.Value; - //unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - System.out.println(big2.Value); - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/37/6066e4dcb14b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/37/6066e4dcb14b00171c69d98bf667dda6 deleted file mode 100644 index 79e18aa..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/37/6066e4dcb14b00171c69d98bf667dda6 +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/38/40fa7d2a604c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/38/40fa7d2a604c0017146ede6da4ae5d42 deleted file mode 100644 index b5359f6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/38/40fa7d2a604c0017146ede6da4ae5d42 +++ /dev/null @@ -1,216 +0,0 @@ -package UnitParser; - -import java.util.AbstractMap; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -public class Prefix implements Comparable -{ - /**Name of the unit prefix.**/ - public final String Name; - /**Symbol of the unit prefix.**/ - public final String Symbol; - /**Multiplying factor associated with the unit prefix.**/ - public final double Factor; - /**Type of the unit prefix.**/ - public final PrefixTypes Type; - /**Usage conditions of the unit prefix.**/ - public final PrefixUsageTypes PrefixUsage; - - /**Initialises a new Prefix instance.**/ - public Prefix() - { - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - PrefixUsage = PrefixUsageTypes.DefaultUsage; - } - - /** - Initialises a new Prefix instance. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - } - - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor) - { - this(factor, PrefixUsageTypes.DefaultUsage); - } - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(factor, ""); - - if (Type != PrefixTypes.None) - { - Factor = factor; - Name = GetName(Type, Factor); - - Symbol = Linq.FirstOrDefaultDict - ( - Type == PrefixTypes.SI ? HCPrefixes.AllSIPrefixSymbols : - HCPrefixes.AllBinaryPrefixSymbols, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(null, 0.0) - ) - .getKey(); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol) - { - this(symbol, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(1.0, symbol); - - if (Type != PrefixTypes.None) - { - Symbol = symbol; - Factor = - ( - Type == PrefixTypes.SI ? - HCPrefixes.AllSIPrefixSymbols.get(symbol) : - HCPrefixes.AllBinaryPrefixSymbols.get(symbol) - ); - Name = GetName(Type, Factor); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name prefix Prefix variable whose information will be used. - **/ - public Prefix(Prefix prefix) - { - if (prefix == null) prefix = new Prefix(); - - Name = prefix.Name; - Symbol = prefix.Symbol; - Factor = prefix.Factor; - Type = prefix.Type; - PrefixUsage = prefix.PrefixUsage; - } - - private static PrefixTypes GetType(double factor, String symbol) - { - PrefixTypes outType = PrefixTypes.None; - if (factor == 1.0 && symbol == "") return outType; - - if (factor != 1.0) - { - if (HCPrefixes.AllSIPrefixes.containsValue(factor)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixes.containsValue(factor)) - { - outType = PrefixTypes.Binary; - } - } - else - { - if (HCPrefixes.AllSIPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.Binary; - } - } - - return outType; - } - - private static String GetName(PrefixTypes type, double factor) - { - return - ( - type == PrefixTypes.SI ? - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) : - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - ) - .getKey().toString(); - } - - @Override - public int compareTo(Prefix other) - { - return new Double(this.Factor).compareTo - ( - new Double(other.Factor) - ); - } - - public boolean Equals(Prefix other) - { - return - ( - other == null ? false : - Equals.PrefixesAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((Prefix)obj); - } - - @Override - public int hashCode() { return 0; } - -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/38/70f1d906b24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/38/70f1d906b24a00171059ebc16969059f deleted file mode 100644 index 25dd256..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/38/70f1d906b24a00171059ebc16969059f +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/39/506e9e2fa94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/39/506e9e2fa94a00171059ebc16969059f deleted file mode 100644 index 9764514..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/39/506e9e2fa94a00171059ebc16969059f +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - System.out.println(outInfo.Parts.get(0).Unit); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - System.out.println(outInfo.Parts.get(0).Unit + " " + outInfo.Parts.get(1).Unit); - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/39/a0b9684a634c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/39/a0b9684a634c0017146ede6da4ae5d42 deleted file mode 100644 index 35bb974..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/39/a0b9684a634c0017146ede6da4ae5d42 +++ /dev/null @@ -1,101 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.Operations.*; - -/**Contains the main information associated with the constituent parts of each unit.**/ -public class UnitPart -{ - /**Unit associated with the current part.**/ - public Units Unit; - /**Prefix information associated with the current part.**/ - public Prefix Prefix; - /**Exponent associated with the current part.**/ - public Integer Exponent; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /**Initialises a new UnitPart instance. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exponent Integer exponent to be used. - **/ - public UnitPart(Units unit, Prefix prefix) - { - this(unit, prefix, 1); - } - - /**Initialises a new UnitPart instance. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exponent Integer exponent to be used. - **/ - public UnitPart(Units unit, Prefix prefix, int exponent) - { - Unit = unit; - Prefix = new Prefix(prefix); - Exponent = exponent; - } - - /** - Initialises a new UnitPart instance. - @param unit Member of the Units enum to be used. - @param exponent Integer exponent to be used. - **/ - public UnitPart(Units unit) - { - this(unit, 1); - } - - /** - Initialises a new UnitPart instance. - @param unit Member of the Units enum to be used. - @param exponent Integer exponent to be used. - **/ - public UnitPart(Units unit, int exponent) - { - Unit = unit; - Prefix = new Prefix(1.0); - Exponent = exponent; - } - - /** - Initialises a new UnitPart instance. - @param unitPart UnitPart variable whose information will be used. - **/ - public UnitPart(UnitPart unitPart) - { - if (unitPart == null) unitPart = new UnitPart(Units.None); - - Unit = unitPart.Unit; - Prefix = new Prefix(unitPart.Prefix); - Exponent = unitPart.Exponent; - } - - /** - Determines whether the current UnitPart instance is equal to other one. - @param other Other variable. - **/ - public boolean Equals(UnitPart other) - { - return - ( - other == null ? false : - Equals.UnitPartsAreEqual(this, other) - ); - } - - /** - Determines whether the current UnitPart instance is equal to other one - @param obj Other variable. - **/ - @Override - public boolean equals(Object obj) - { - return Equals((UnitPart)obj); - } - - @Override - /**Returns the hash code for this UnitPart instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/39/f067b59f294a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/39/f067b59f294a001712d4a4f7b050cac8 deleted file mode 100644 index cfc477f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/39/f067b59f294a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1382 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3a/700435b18f4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3a/700435b18f4a00171930ee4d171ed0de deleted file mode 100644 index 78ac099..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3a/700435b18f4a00171930ee4d171ed0de +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - System.out.println(firstInfo.Value + " " + firstInfo.BaseTenExponent + " " + firstInfo.Prefix.Factor + " -- " + secondInfo.Value + " " + secondInfo.BaseTenExponent + " " + secondInfo.Prefix.Factor); - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3a/906f9ce3594c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3a/906f9ce3594c0017146ede6da4ae5d42 deleted file mode 100644 index 13dd213..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3a/906f9ce3594c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1164 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3c/008e82932d4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3c/008e82932d4a001712d4a4f7b050cac8 deleted file mode 100644 index 6102506..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3c/008e82932d4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1032 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3c/40ed1c9b9b4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3c/40ed1c9b9b4a00171930ee4d171ed0de deleted file mode 100644 index 8184eab..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3c/40ed1c9b9b4a00171930ee4d171ed0de +++ /dev/null @@ -1,1858 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - System.out.println(targetInfo.Value); - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - //System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3c/f096eec72f4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3c/f096eec72f4a001712d4a4f7b050cac8 deleted file mode 100644 index 4c99c29..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3c/f096eec72f4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1869 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - if(result == 0) - { - System.out.println("here"); - } - - return - ( - result - //result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - //new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - if(unitInfo.Parts.size() == 2) - { - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - } - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3d/20fca9cef34c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3d/20fca9cef34c00171048b3f61ecb42d3 deleted file mode 100644 index cdb25d2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3d/20fca9cef34c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1224 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList variable including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList variable including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList variable including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList variable including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3d/901f813abb4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3d/901f813abb4a0017160ae291ab4667e2 deleted file mode 100644 index fd16e18..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3d/901f813abb4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine().trim(); - System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3e/10e5edffbb4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3e/10e5edffbb4a0017160ae291ab4667e2 deleted file mode 100644 index 07c809e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3e/10e5edffbb4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3e/50f928acb24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3e/50f928acb24a00171059ebc16969059f deleted file mode 100644 index 2a94994..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3e/50f928acb24a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - System.out.println(outInfo.Value); - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3e/805bab84934a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3e/805bab84934a00171930ee4d171ed0de deleted file mode 100644 index 4ac397d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/3e/805bab84934a00171930ee4d171ed0de +++ /dev/null @@ -1,566 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/40/50a27c10694c00171a25ec0b13e7f3ac b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/40/50a27c10694c00171a25ec0b13e7f3ac deleted file mode 100644 index 04d1c60..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/40/50a27c10694c00171a25ec0b13e7f3ac +++ /dev/null @@ -1,1203 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - ///Determines whether the current ErrorInfo instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this ErrorInfo instance. - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - ///Determines whether the current UnitP instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this UnitP instance. - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/40/c04d989d6d4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/40/c04d989d6d4c00171838d4a3813404a0 deleted file mode 100644 index db44724..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/40/c04d989d6d4c00171838d4a3813404a0 +++ /dev/null @@ -1,261 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - if (input == null) return defaultVal; - - ArrayList tempVar = - ( - filter == null ? input : - Where(input, filter) - ); - if (tempVar == null) return defaultVal; - - return GetFirst(input2, filter, defaultVal); ; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = - ( - filter == null ? input : - WhereDict(input, filter) - ); - if (tempVar == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(tempVar), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/41/506e4117b44b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/41/506e4117b44b00171c69d98bf667dda6 deleted file mode 100644 index 4937696..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/41/506e4117b44b00171c69d98bf667dda6 +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/41/a02076a6b64b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/41/a02076a6b64b00171c69d98bf667dda6 deleted file mode 100644 index 0c2fd86..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/41/a02076a6b64b00171c69d98bf667dda6 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - System.out.println(parts2.get(0).Unit + " " + parts2.get(0).Exponent.toString() + " " + parts2.get(1).Unit + " " + parts2.get(1).Exponent.toString()); - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/42/b0c1781a9a4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/42/b0c1781a9a4a00171930ee4d171ed0de deleted file mode 100644 index 01753d7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/42/b0c1781a9a4a00171930ee4d171ed0de +++ /dev/null @@ -1,1032 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/42/f01c0419644c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/42/f01c0419644c0017146ede6da4ae5d42 deleted file mode 100644 index 2d1fc56..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/42/f01c0419644c0017146ede6da4ae5d42 +++ /dev/null @@ -1,436 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - System.out.println("Condition 2 true"); - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/43/7001c1a95c4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/43/7001c1a95c4c0017146ede6da4ae5d42 deleted file mode 100644 index ec40331..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/43/7001c1a95c4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,164 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - System.out.println(UnitPNonUnitInfoAreEqual(first, second)); - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return (first.Error.equals(second.Error)); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type != ErrorTypes.None || secondInfo.Error.Type != ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - System.out.println(first.Type + " " + first.ExceptionHandling + " -- " + second.Type + " " + second.ExceptionHandling); - return - ( - first.ExceptionHandling.equals(second.ExceptionHandling) && - first.Type.equals(second.Type) - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/44/80234707654c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/44/80234707654c0017146ede6da4ae5d42 deleted file mode 100644 index 176047c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/44/80234707654c0017146ede6da4ae5d42 +++ /dev/null @@ -1,436 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix.equals(new UnitP(1.0, "ks").UnitPrefix)) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton).equals(new UnitP("1 Mg*m/s2"))) - { - System.out.println("Condition 7 true"); - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/44/b0438a10b54b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/44/b0438a10b54b00171c69d98bf667dda6 deleted file mode 100644 index 798eb56..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/44/b0438a10b54b00171c69d98bf667dda6 +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/44/e0b4f261294a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/44/e0b4f261294a001712d4a4f7b050cac8 deleted file mode 100644 index 6a5e1ce..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/44/e0b4f261294a001712d4a4f7b050cac8 +++ /dev/null @@ -1,15 +0,0 @@ -package test0; - -import UnitParser.UnitP; -import UnitParser.Units; -import UnitParser.UnitP.ErrorInfo; -import UnitParser.UnitP.ErrorTypes; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP("1234E1.5"); - System.out.println(test.Error.Type); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/10a8c2c16f4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/10a8c2c16f4c00171838d4a3813404a0 deleted file mode 100644 index 89df8d8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/10a8c2c16f4c00171838d4a3813404a0 +++ /dev/null @@ -1,254 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return 0; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || input.entrySet() == null || filter == null) - { - return new ArrayList(); - } - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.entrySet() == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/e056a48ff54c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/e056a48ff54c00171048b3f61ecb42d3 deleted file mode 100644 index 0635ce9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/e056a48ff54c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1238 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - @return Current instance converted to targetUnit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return Current instance converted to targetUnit and targetPrefix. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - @return Current instance converted to targetUnitString. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance unit. - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance unit. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance type. - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance type. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance type and system. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance type and system. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - @return ArrayList including all the units associated with the current instance type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - @return ArrayList including all the units associated with the current instance type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - @return UnitTypes variable associated with the current instance. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - @return UnitSystems variable associated with the current instance. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - @return Removes the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0) from the current instance. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/e0d54ebe314a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/e0d54ebe314a001712d4a4f7b050cac8 deleted file mode 100644 index c8a9e0a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/e0d54ebe314a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1872 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - - Map.Entry res11 = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ); - - Map.Entry res12 = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ); - - - //Original C# code -> .ThenByDescending(x => x.Exponent) - int res2 = new Integer(second.Exponent).compareTo(first.Exponent); - if (res11 == null && res12 == null) - { - return res2; - } - - return res2; - - //int res1 = res11.getValue().compareTo(res12.getValue()); - - //return - //( - // res1 != 0 ? res1 : res2 - //); - } - } - ); - - if(unitInfo.Parts.size() == 2) - { - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - } - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/f0325af6b24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/f0325af6b24a00171059ebc16969059f deleted file mode 100644 index 18a6a3a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/45/f0325af6b24a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - System.out.println("asfasdfasf"); - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/1052632a7b4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/1052632a7b4c00171945f16efe0d9b5d deleted file mode 100644 index 63d2868..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/1052632a7b4c00171945f16efe0d9b5d +++ /dev/null @@ -1,1052 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -@SuppressWarnings("serial") -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = (int)Math.signum(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - tempInfo = Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/302378d1574f001719569dd272852f7b b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/302378d1574f001719569dd272852f7b deleted file mode 100644 index 27ba9b7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/302378d1574f001719569dd272852f7b +++ /dev/null @@ -1,434 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix.equals(new UnitP(1.0, "ks").UnitPrefix)) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton).equals(new UnitP("1 Mg*m/s2"))) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/30d7615a9a4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/30d7615a9a4a00171930ee4d171ed0de deleted file mode 100644 index 76a5abc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/30d7615a9a4a00171930ee4d171ed0de +++ /dev/null @@ -1,1032 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/500d5e7c514c00171860ae6a5189088d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/500d5e7c514c00171860ae6a5189088d deleted file mode 100644 index 86e0853..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/500d5e7c514c00171860ae6a5189088d +++ /dev/null @@ -1,82 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".") || input.toLowerCase().contains("e")) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input) throws Exception - { - if - ( - input == null || Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(input.toLowerCase()), x -> !Character.isDigit(x) && - x != '.' && x != ',' && x != 'e' && x != '-' && x != '+', '\u0000' - ) - != '\u0000' - ) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - //Note that TryParseOutput analyses the exponential cases (i.e., including e + integer exponent) further. - throw new Exception(); - } - - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/b08b6b5eb24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/b08b6b5eb24a00171059ebc16969059f deleted file mode 100644 index ce000e7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/b08b6b5eb24a00171059ebc16969059f +++ /dev/null @@ -1,1055 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - System.out.println(originalInfo.Value); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/c066df49314a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/c066df49314a001712d4a4f7b050cac8 deleted file mode 100644 index d075af9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/46/c066df49314a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1872 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - - Map.Entry res11 = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ); - - Map.Entry res12 = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ); - - - //Original C# code -> .ThenByDescending(x => x.Exponent) - int res2 = new Integer(second.Exponent).compareTo(first.Exponent); - if (res11 == null && res12 == null) - { - return res2; - } - - return res2; - - int res1 = res11.getValue().compareTo(res12.getValue()); - - return - ( - res1 != 0 ? res1 : res2 - ); - } - } - ); - - if(unitInfo.Parts.size() == 2) - { - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - } - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/47/d094bd80ba4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/47/d094bd80ba4a0017160ae291ab4667e2 deleted file mode 100644 index 07c809e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/47/d094bd80ba4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/49/a003b3bab44b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/49/a003b3bab44b00171c69d98bf667dda6 deleted file mode 100644 index 7ff732e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/49/a003b3bab44b00171c69d98bf667dda6 +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4a/40e7506ac14a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4a/40e7506ac14a00171634abff01ee97d5 deleted file mode 100644 index e8f3a3f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4a/40e7506ac14a00171634abff01ee97d5 +++ /dev/null @@ -1,18 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4a/b0fcb43a6f4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4a/b0fcb43a6f4c00171838d4a3813404a0 deleted file mode 100644 index aab90d7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4a/b0fcb43a6f4c00171838d4a3813404a0 +++ /dev/null @@ -1,251 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return null; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || filter == null) return new ArrayList(); - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), filter, defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4a/f029451fb24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4a/f029451fb24a00171059ebc16969059f deleted file mode 100644 index 75a4817..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4a/f029451fb24a00171059ebc16969059f +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - System.out.println(originalInfo.Value); - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/00fd54b42a4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/00fd54b42a4a001712d4a4f7b050cac8 deleted file mode 100644 index 42a269f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/00fd54b42a4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1164 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/5078d463994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/5078d463994a00171930ee4d171ed0de deleted file mode 100644 index 0627ec8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/5078d463994a00171930ee4d171ed0de +++ /dev/null @@ -1,1166 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - //System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent + " " + parseInfo.UnitInfo.Prefix.Factor); - System.out.println("asfasdfa"); - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/8079120e8f4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/8079120e8f4a00171930ee4d171ed0de deleted file mode 100644 index 34ad7ac..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/8079120e8f4a00171930ee4d171ed0de +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/c089b1442b4c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/c089b1442b4c00171ae7fcf2c321c986 deleted file mode 100644 index 7c2f632..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/c089b1442b4c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = (int)Math.signum(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - System.out.println(unitInfo.Parts.get(i).Exponent + " " + parts2.get(0).Exponent); - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/f0416c7b9e4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/f0416c7b9e4a00171930ee4d171ed0de deleted file mode 100644 index 083ca64..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4c/f0416c7b9e4a00171930ee4d171ed0de +++ /dev/null @@ -1,328 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - X output = null; - try - { - output = GetFirst - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return output; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal, ExceptionTypes type) throws Exception - { - if (input == null) - { - return GetDefaultOrException(defaultVal, type); - } - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return GetDefaultOrException(defaultVal, type); - } - - private static X GetDefaultOrException(X defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - public static Map.Entry FirstDict(HashMap input) throws Exception - { - return FirstDict(input, null); - } - - public static Map.Entry FirstDict(HashMap input, Predicate> filter) throws Exception - { - if (filter != null) input = WhereDict(input, filter); - - return GetFirstDict - ( - input, filter, null, ExceptionTypes.FirstDict - ); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = input; - if (filter != null) - { - tempVar = WhereDict(input, filter); - } - if (tempVar == null) return defaultVal; - - HashMap input2 = new HashMap(tempVar); - - try - { - return GetFirstDict - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return defaultVal; - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal, ExceptionTypes type - ) - throws Exception - { - if (input == null) - { - return GetDefaultOrExceptionDict(defaultVal, type); - } - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return GetDefaultOrExceptionDict(defaultVal, type); - } - - private static Map.Entry GetDefaultOrExceptionDict(Map.Entry defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - private static void ThrowException(ExceptionTypes type) throws Exception - { - String method = "First"; - if (type == ExceptionTypes.FirstDict) - { - method = " (1-D collections)"; - } - else if (type == ExceptionTypes.First) - { - method = " (dictionaries)"; - } - - throw new Exception("Exception provoked by an error in the custom version of the " + method + " LINQ method."); - } - - enum ExceptionTypes { None, First, FirstDict } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4d/a0f4bea8b54b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4d/a0f4bea8b54b00171c69d98bf667dda6 deleted file mode 100644 index f3093ea..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4d/a0f4bea8b54b00171c69d98bf667dda6 +++ /dev/null @@ -1,1387 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Parts.size() == 2) - { - //System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent); - System.out.println(parseInfo.UnitInfo.Parts.get(0).Unit + " " + parseInfo.UnitInfo.Parts.get(1).Unit); - } - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4e/90efca3bb94a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4e/90efca3bb94a0017160ae291ab4667e2 deleted file mode 100644 index ce9a77e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4e/90efca3bb94a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.next(); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - System.out.println("here"); - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4e/e09b699f2c4c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4e/e09b699f2c4c00171ae7fcf2c321c986 deleted file mode 100644 index 4eac353..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4e/e09b699f2c4c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = (int)Math.signum(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - System.out.println(exponent); - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4f/9011718a504c00171860ae6a5189088d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4f/9011718a504c00171860ae6a5189088d deleted file mode 100644 index 9a1c92b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/4f/9011718a504c00171860ae6a5189088d +++ /dev/null @@ -1,12 +0,0 @@ -package test0; - -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP("J÷s-2"); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5/801062cc994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5/801062cc994a00171930ee4d171ed0de deleted file mode 100644 index c9322a3..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5/801062cc994a00171930ee4d171ed0de +++ /dev/null @@ -1,137 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - System.out.println(UnitInfo.Value + " " + UnitInfo.BaseTenExponent + " " + UnitInfo.Prefix.Factor); - - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = - ( - improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - UnitInfo.Value - ); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5/f080579ac84a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5/f080579ac84a00171634abff01ee97d5 deleted file mode 100644 index b45beb8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5/f080579ac84a00171634abff01ee97d5 +++ /dev/null @@ -1,18 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/3022a4e5b34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/3022a4e5b34a00171059ebc16969059f deleted file mode 100644 index 00c8a9b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/3022a4e5b34a00171059ebc16969059f +++ /dev/null @@ -1,1062 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - UnitInfo test = Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - System.out.println(test.Value + " asdfasdf"); - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/30c6e825a94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/30c6e825a94a00171059ebc16969059f deleted file mode 100644 index fff252d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/30c6e825a94a00171059ebc16969059f +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - System.out.println(outInfo.Parts.get(0).Unit); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - System.out.println(outInfo.Parts.get(1).Unit); - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/90e20f82b34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/90e20f82b34a00171059ebc16969059f deleted file mode 100644 index 5355d2b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/90e20f82b34a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - System.out.println(outInfo.Value); - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/b02b0f34b64b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/b02b0f34b64b00171c69d98bf667dda6 deleted file mode 100644 index dc43fb9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/b02b0f34b64b00171c69d98bf667dda6 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/d0a341dba94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/d0a341dba94a00171059ebc16969059f deleted file mode 100644 index a89f38f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/50/d0a341dba94a00171059ebc16969059f +++ /dev/null @@ -1,1382 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - System.out.println(parseInfo.UnitInfo.Unit); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/51/10b98014324a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/51/10b98014324a001712d4a4f7b050cac8 deleted file mode 100644 index 16bc964..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/51/10b98014324a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1867 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - - - Integer res11 = unitInfo.InitialPositions.get(first); - - Integer res12 = unitInfo.InitialPositions.get(second); - - - //Original C# code -> .ThenByDescending(x => x.Exponent) - int res2 = new Integer(second.Exponent).compareTo(first.Exponent); - //if (res11 == null && res12 == null) - //{ - // return res2; - //} - - return res2; - - //int res1 = res11.getValue().compareTo(res12.getValue()); - - //return - //( - // res1 != 0 ? res1 : res2 - //); - } - } - ); - - if(unitInfo.Parts.size() == 2) - { - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - } - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/51/5037c5499a4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/51/5037c5499a4a00171930ee4d171ed0de deleted file mode 100644 index 1492f6d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/51/5037c5499a4a00171930ee4d171ed0de +++ /dev/null @@ -1,1032 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/51/801b123e2c4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/51/801b123e2c4a001712d4a4f7b050cac8 deleted file mode 100644 index 4f9dbbc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/51/801b123e2c4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,135 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - System.out.println("asdfasdf"); - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = - ( - improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - UnitInfo.Value - ); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/52/3097c977f84c001712ece6513f6adb77 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/52/3097c977f84c001712ece6513f6adb77 deleted file mode 100644 index f011230..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/52/3097c977f84c001712ece6513f6adb77 +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/52/6051121b414c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/52/6051121b414c00171eb8e3cba3fc21fa deleted file mode 100644 index 23d12a5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/52/6051121b414c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,70 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - System.out.println(input + " " + output.IsOK); - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //Emulating the conditions of the original C# version where decimal numbers cannot be parsed as integer. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input) throws ParseException - { - //Locale.US because of being the best equivalence for CultureInfo.InvariantCulture in the original C# code. - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/53/b03b3a35994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/53/b03b3a35994a00171930ee4d171ed0de deleted file mode 100644 index 13dd213..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/53/b03b3a35994a00171930ee4d171ed0de +++ /dev/null @@ -1,1164 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/56/10935b01b24b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/56/10935b01b24b00171c69d98bf667dda6 deleted file mode 100644 index bbf3651..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/56/10935b01b24b00171c69d98bf667dda6 +++ /dev/null @@ -1,244 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - System.out.println(outInfo.Value + " " + outInfo.BaseTenExponent); - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/56/408cf2715d4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/56/408cf2715d4c0017146ede6da4ae5d42 deleted file mode 100644 index c7af3e5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/56/408cf2715d4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,162 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return (first.Error.equals(second.Error)); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type.equals(ErrorTypes.None) || secondInfo.Error.Type.equals(ErrorTypes.None)) - { - return firstInfo.Error.Type.equals(secondInfo.Error.Type); - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent.equals(secondInfo.BaseTenExponent) && - firstInfo.Value.equals(secondInfo.Value) - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling == second.ExceptionHandling && - first.Type == second.Type - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/57/a0a7ab3fe74c00171118892245944c7f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/57/a0a7ab3fe74c00171118892245944c7f deleted file mode 100644 index ecb6fb9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/57/a0a7ab3fe74c00171118892245944c7f +++ /dev/null @@ -1,254 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -//Class including Java custom versions for all the System.Linq methods used in the original C# code. -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return 0; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || input.entrySet() == null || filter == null) - { - return new ArrayList(); - } - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.entrySet() == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/58/302922332d4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/58/302922332d4a001712d4a4f7b050cac8 deleted file mode 100644 index 62928e2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/58/302922332d4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1858 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - System.out.println(unitPart.Exponent); - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/59/400efc19b34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/59/400efc19b34a00171059ebc16969059f deleted file mode 100644 index 05e6197..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/59/400efc19b34a00171059ebc16969059f +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/59/e0486a4ab64b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/59/e0486a4ab64b00171c69d98bf667dda6 deleted file mode 100644 index 52380b5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/59/e0486a4ab64b00171c69d98bf667dda6 +++ /dev/null @@ -1,1387 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Parts.size() == 2) - { - //System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent); - System.out.println(parseInfo.UnitInfo.Parts.get(0).Unit + " " + parseInfo.UnitInfo.Parts.get(1).Unit); - } - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5a/f06dfedfbc4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5a/f06dfedfbc4a0017160ae291ab4667e2 deleted file mode 100644 index 5ce21f4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5a/f06dfedfbc4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5b/50746376f44c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5b/50746376f44c00171048b3f61ecb42d3 deleted file mode 100644 index d8d6cdc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5b/50746376f44c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1225 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - @return Updating current instance to include the information resulting from converting unitP to targetUnit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5c/102f2bcda84a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5c/102f2bcda84a00171059ebc16969059f deleted file mode 100644 index 8a9b0cf..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5c/102f2bcda84a00171059ebc16969059f +++ /dev/null @@ -1,245 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - System.out.println - ( - outInfo.Value + " " + outInfo.BaseTenExponent + " " + outInfo.Prefix.Factor + " -- " + - secondInfo.Value + " " + secondInfo.BaseTenExponent + " " + secondInfo.Prefix.Factor - ); - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5c/c0f3ab42414c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5c/c0f3ab42414c00171eb8e3cba3fc21fa deleted file mode 100644 index 3cba920..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5c/c0f3ab42414c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,70 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //Emulating the conditions of the original C# version where decimal numbers cannot be parsed as integer. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - System.out.println(input + " " + output.IsOK); - - return output; - } - - static Number ParseCommon(String input) throws ParseException - { - //Locale.US because of being the best equivalence for CultureInfo.InvariantCulture in the original C# code. - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5e/10156bdbba4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5e/10156bdbba4a0017160ae291ab4667e2 deleted file mode 100644 index 36bc591..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5e/10156bdbba4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner("System.in"); - String input = scanner.nextLine(); - System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5e/c01de7bd7e4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5e/c01de7bd7e4c00171945f16efe0d9b5d deleted file mode 100644 index c349e4b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5e/c01de7bd7e4c00171945f16efe0d9b5d +++ /dev/null @@ -1,102 +0,0 @@ -package InternalUnitParser.Operations; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class OperationsOther -{ - public static String GetOperationString(UnitP first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(UnitP first, Double second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), second.toString(), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(Double first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - first.toString(), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - private static String GetUnitPString(UnitP unitP) - { - return unitP.OriginalUnitString; - } - - private static String ConcatenateOperationString(String first, String second, char operation) - { - return (first + " " + operation + " " + second); - } - - //NOTE: the order within each char[] collection does matter. The first element will be treated as the default - //symbol for the given operation (e.g., used when creating a String including that operation). - public static HashMap> OperationSymbols; - - public static ArrayList UnitParseIgnored; - - public static final double MaxValue = 79228162514264337593543950335.0; //C# Decimal.MaxValue actual value. - public static final double MinValue = 0.0000000000000000000000000001; //C# Decimal precision lowest limit. - - public static String Start() - { - OperationSymbols = new HashMap>() - { - { - { - put - ( - Operations.Addition, new ArrayList() - {{ - add('+'); - }} - ); - put - ( - Operations.Subtraction, new ArrayList() - {{ - add('-'); add('−'); add('—'); - }} - ); - put - ( - Operations.Multiplication, new ArrayList() - {{ - add('*'); add('x'); add('X'); add('×'); add('⊗'); add('â‹…'); add('·'); - }} - ); - put - ( - Operations.Division, new ArrayList() - {{ - add('/'); add('∕'); - //add('/'); add('∕'); add('â„'); add('÷'); add('|'); add('\\'); - }} - ); - } - } - }; - - UnitParseIgnored = new ArrayList() - {{ - add("."); add(","); add(":"); add(";"); add("_"); add("^"); add("+"); - add("#"); add("("); add(")"); add("["); add("]"); add("{"); add("}"); - add("="); add("!"); add("?"); add("@"); add("&"); - }}; - - return ""; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5f/9041308a5c4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5f/9041308a5c4c0017146ede6da4ae5d42 deleted file mode 100644 index c6757f7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5f/9041308a5c4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,164 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - System.out.println(UnitPNonUnitInfoAreEqual(first, second)); - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return (first.Error.equals(second.Error)); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type != ErrorTypes.None || secondInfo.Error.Type != ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - System.out.println(first.Type + " " + first.ExceptionHandling + " -- " + second.Type + " " + second.ExceptionHandling)); - return - ( - first.ExceptionHandling.equals(second.ExceptionHandling) && - first.Type.equals(second.Type) - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5f/e0c1c2f7294a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5f/e0c1c2f7294a001712d4a4f7b050cac8 deleted file mode 100644 index 7cc1d53..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5f/e0c1c2f7294a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - System.out.println(parseInfo.UnitInfo.Parts.get(0).Unit); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5f/e0d4ebe0614c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5f/e0d4ebe0614c0017146ede6da4ae5d42 deleted file mode 100644 index 4580f4e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/5f/e0d4ebe0614c0017146ede6da4ae5d42 +++ /dev/null @@ -1,165 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return - ( - first.Error.equals(second.Error) - ); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type == ErrorTypes.None || secondInfo.Error.Type == ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling == second.ExceptionHandling && - first.Type == second.Type - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6/80ff3669f54c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6/80ff3669f54c00171048b3f61ecb42d3 deleted file mode 100644 index 16b5564..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6/80ff3669f54c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1237 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - @return Current instance converted to targetUnit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return Current instance converted to targetUnit and targetPrefix. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - @return Current instance converted to targetUnitString. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance unit. - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance unit. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance type. - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance type. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance type and system. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance type and system. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - @return ArrayList including all the units associated with the current instance type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - @return ArrayList including all the units associated with the current instance type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - @return UnitTypes variable associated with the current instance. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - @return UnitSystems variable associated with the current instance. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6/a07037432d4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6/a07037432d4a001712d4a4f7b050cac8 deleted file mode 100644 index 3b52ae4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6/a07037432d4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1859 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.Parts.get(1).Exponent); - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/60/6027c5cd644c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/60/6027c5cd644c0017146ede6da4ae5d42 deleted file mode 100644 index 66c31fd..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/60/6027c5cd644c0017146ede6da4ae5d42 +++ /dev/null @@ -1,436 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - System.out.println("Condition 6 true"); - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/61/104d1fe3a84a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/61/104d1fe3a84a00171059ebc16969059f deleted file mode 100644 index 191a7b7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/61/104d1fe3a84a00171059ebc16969059f +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - System.out.println(first.Parts.size()); - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - System.out.println(outInfo.Parts.size()); - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/61/5061dfb1a74a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/61/5061dfb1a74a00171059ebc16969059f deleted file mode 100644 index 52ba06b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/61/5061dfb1a74a00171059ebc16969059f +++ /dev/null @@ -1,21 +0,0 @@ -package test0; - -import java.util.Comparator; -import java.util.HashMap; - -import InternalUnitParser.CSharpAdaptation.Linq; -import InternalUnitParser.Hardcoding.HCPrefixes; -import UnitParser.UnitP; -import UnitParser.UnitSymbols; - -public class Main -{ - public static void main(String[] args) throws Exception - { - - - UnitP test = UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")); - //UnitP.Addition(UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ")); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/63/70261c30f14c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/63/70261c30f14c00171048b3f61ecb42d3 deleted file mode 100644 index 955702a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/63/70261c30f14c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1210 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP instance including the information resulting from the intended conversion. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/63/b0ba318ba94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/63/b0ba318ba94a00171059ebc16969059f deleted file mode 100644 index 095d662..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/63/b0ba318ba94a00171059ebc16969059f +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/63/b0e74b0d5c4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/63/b0e74b0d5c4c0017146ede6da4ae5d42 deleted file mode 100644 index 7bff27a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/63/b0e74b0d5c4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,163 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - System.out.println(UnitPNonUnitInfoAreEqual(first, second)); - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return (first.Error == second.Error); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type != ErrorTypes.None || secondInfo.Error.Type != ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling == second.ExceptionHandling && - first.Type == second.Type - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/64/40fa33b3674c00171a25ec0b13e7f3ac b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/64/40fa33b3674c00171a25ec0b13e7f3ac deleted file mode 100644 index 28accb7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/64/40fa33b3674c00171a25ec0b13e7f3ac +++ /dev/null @@ -1,29 +0,0 @@ -package test0; - -import java.util.ArrayList; -import java.util.Collections; - -import UnitParser.*; - -public class Main -{ - public static void main(String[] args) throws Exception - { - ArrayList tests = new ArrayList(); - tests.add(new Prefix(22.0)); - tests.add(new Prefix(1000.0)); - tests.add(new Prefix(555.0)); - - if(tests.get(0).equals(tests.get(2))) - { - System.out.println("Is OK"); - } - - Collections.sort(tests); - - for (Prefix item: tests) - { - System.out.println(item.Factor); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/64/8050249f634c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/64/8050249f634c0017146ede6da4ae5d42 deleted file mode 100644 index 53387e9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/64/8050249f634c0017146ede6da4ae5d42 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/64/f07929ea794c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/64/f07929ea794c00171945f16efe0d9b5d deleted file mode 100644 index e063170..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/64/f07929ea794c00171945f16efe0d9b5d +++ /dev/null @@ -1,2630 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; - -import java.util.AbstractMap; -import java.util.HashMap; -import java.util.stream.Collectors; - - -@SuppressWarnings("serial") -public class HCMain -{ - //Main classification for all the units (type, system and conversion factor). - //This dictionary represents an easily-modifiable container of well-structured unit information. - //After using all this information to create more specific/efficient collections, GetAllMain() deletes it. - public static HashMap>> AllUnits; - - /** - HashMap mostly meant to deal with the Imperial/USCS peculiar relationship. - **/ - public static HashMap AllBasicSystems; - - /** - Some times, all what matters is knowing whether the system is metric (SI/CGS) or English (Imperial/USCS). - **/ - public static HashMap AllMetricEnglish; - - /** - This collection relates all the unnamed units with their associated systems. - There are many units which don't fit any Units enum case, the unnamed units. - Unnamed units avoid a huge (and not too logical) hardcoding effort. - Note that UnitParser supports much more units than just the members of the Units enum. - By bearing in mind that any combination of named units forming a supported type is also - supported, the total number of supported units is way too big to even think about facing - it in a hardcoding-all-of-them way. - **/ - public static HashMap DefaultUnnamedUnits; - - /** - Relates all the units with their respective types. - The call to GetALLMain() also populates all the collections below this line. - **/ - public static HashMap AllUnitTypes; - - /**Relates all the units with their respective systems.**/ - public static HashMap AllUnitSystems; - - /**Relates all the units with their respective conversion factors.**/ - public static HashMap AllUnitConversionFactors; - - /**Includes all the supported unit string representations (case doesn't matter).**/ - public static HashMap AllUnitStrings; - - /**Includes secondary symbols for some units (case does matter).**/ - public static HashMap AllUnitSymbols2; - - /**Some conversion factors are too small/big for the decimal type.**/ - public static HashMap AllBeyondDecimalConversionFactors; - - public static void Start() - { - AllUnits = new HashMap>>() - { - { - put - ( - UnitTypes.None, - new HashMap>() - { - { - put - ( - UnitSystems.SI, new HashMap() - { - { put(Units.ValidSIUnit, 1.0); } - } - ); - put - ( - UnitSystems.Imperial, new HashMap() - { - { put(Units.ValidImperialUSCSUnit, 1.0); put(Units.ValidImperialUnit, 1.0); } - } - ); - put - ( - UnitSystems.USCS, new HashMap() - { - { put(Units.ValidUSCSUnit, 1.0); } - } - ); - put - ( - UnitSystems.CGS, new HashMap() - { - { put(Units.ValidCGSUnit, 1.0); } - } - ); - put - ( - UnitSystems.None, new HashMap() - { - { put(Units.ValidUnit, 1.0); put(Units.Unitless, 1.0); } - } - ); - } - } - ); - put - ( - UnitTypes.Length, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Metre, UnitConversionFactors.Metre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Centimetre, UnitConversionFactors.Centimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Foot, UnitConversionFactors.Foot); - put(Units.Thou, UnitConversionFactors.Thou); - put(Units.Mil, UnitConversionFactors.Mil); - put(Units.Inch, UnitConversionFactors.Inch); - put(Units.Yard, UnitConversionFactors.Yard); - put(Units.Fathom, UnitConversionFactors.Fathom); - put(Units.Rod, UnitConversionFactors.Rod); - put(Units.Perch, UnitConversionFactors.Perch); - put(Units.Pole, UnitConversionFactors.Pole); - put(Units.Chain, UnitConversionFactors.Chain); - put(Units.Furlong, UnitConversionFactors.Furlong); - put(Units.Mile, UnitConversionFactors.Mile); - put(Units.Link, UnitConversionFactors.Link); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.SurveyInch, UnitConversionFactors.SurveyInch); - put(Units.SurveyFoot, UnitConversionFactors.SurveyFoot); - put(Units.SurveyYard, UnitConversionFactors.SurveyYard); - put(Units.SurveyRod, UnitConversionFactors.SurveyRod); - put(Units.SurveyChain, UnitConversionFactors.SurveyChain); - put(Units.SurveyLink, UnitConversionFactors.SurveyLink); - put(Units.SurveyMile, UnitConversionFactors.SurveyMile); - put(Units.SurveyFathom, UnitConversionFactors.SurveyFathom); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.AstronomicalUnit, UnitConversionFactors.AstronomicalUnit); - put(Units.NauticalMile, UnitConversionFactors.NauticalMile); - put(Units.Angstrom, UnitConversionFactors.Angstrom); - put(Units.Fermi, UnitConversionFactors.Fermi); - put(Units.LightYear, UnitConversionFactors.LightYear); - put(Units.Parsec, UnitConversionFactors.Parsec); - put(Units.Micron, UnitConversionFactors.Micron); - } - } - ); - } - } - ); - put - ( - UnitTypes.Mass, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Gram, UnitConversionFactors.Gram); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Pound, UnitConversionFactors.Pound); - put(Units.Grain, UnitConversionFactors.Grain); - put(Units.Drachm, UnitConversionFactors.Drachm); - put(Units.Ounce, UnitConversionFactors.Ounce); - put(Units.Stone, UnitConversionFactors.Stone); - put(Units.Slug, UnitConversionFactors.Slug); - put(Units.Quarter, UnitConversionFactors.Quarter); - put(Units.LongQuarter, UnitConversionFactors.LongQuarter); - put(Units.Hundredweight, UnitConversionFactors.Hundredweight); - put(Units.LongHundredweight, UnitConversionFactors.LongHundredweight); - put(Units.Ton, UnitConversionFactors.Ton); - put(Units.LongTon, UnitConversionFactors.LongTon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.ShortQuarter, UnitConversionFactors.ShortQuarter); - put(Units.ShortHundredweight, UnitConversionFactors.ShortHundredweight); - put(Units.ShortTon, UnitConversionFactors.ShortTon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.MetricTon, UnitConversionFactors.MetricTon); - put(Units.Dalton, UnitConversionFactors.Dalton); - put(Units.UnifiedAtomicMassUnit, UnitConversionFactors.UnifiedAtomicMassUnit); - put(Units.Carat, UnitConversionFactors.Carat); - } - } - ); - } - } - ); - put - ( - UnitTypes.Time, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Second, UnitConversionFactors.Second); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Minute, UnitConversionFactors.Minute); - put(Units.Hour, UnitConversionFactors.Hour); - put(Units.Day, UnitConversionFactors.Day); - put(Units.Shake, UnitConversionFactors.Shake); - } - } - ); - } - } - ); - put - ( - UnitTypes.Area, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquareMetre, UnitConversionFactors.SquareMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.SquareCentimetre, UnitConversionFactors.SquareCentimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.SquareFoot, UnitConversionFactors.SquareFoot); - put(Units.SquareInch, UnitConversionFactors.SquareInch); - put(Units.SquareRod, UnitConversionFactors.SquareRod); - put(Units.SquarePerch, UnitConversionFactors.SquarePerch); - put(Units.SquarePole, UnitConversionFactors.SquarePole); - put(Units.Rood, UnitConversionFactors.Rood); - put(Units.Acre, UnitConversionFactors.Acre); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.SurveyAcre, UnitConversionFactors.SurveyAcre); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Are, UnitConversionFactors.Are); - put(Units.Barn, UnitConversionFactors.Barn); - } - } - ); - } - } - ); - put - ( - UnitTypes.Volume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetre, UnitConversionFactors.CubicMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.CubicCentimetre, UnitConversionFactors.CubicCentimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.CubicFoot, UnitConversionFactors.CubicFoot); - put(Units.CubicInch, UnitConversionFactors.CubicInch); - put(Units.FluidOunce, UnitConversionFactors.FluidOunce); - put(Units.ImperialFluidOunce, UnitConversionFactors.ImperialFluidOunce); - put(Units.Gill, UnitConversionFactors.Gill); - put(Units.ImperialGill, UnitConversionFactors.ImperialGill); - put(Units.Pint, UnitConversionFactors.Pint); - put(Units.ImperialPint, UnitConversionFactors.ImperialPint); - put(Units.Quart, UnitConversionFactors.Quart); - put(Units.ImperialQuart, UnitConversionFactors.ImperialQuart); - put(Units.Gallon, UnitConversionFactors.Gallon); - put(Units.ImperialGallon, UnitConversionFactors.ImperialGallon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.USCSFluidOunce, UnitConversionFactors.USCSFluidOunce); - put(Units.USCSGill, UnitConversionFactors.USCSGill); - put(Units.LiquidPint, UnitConversionFactors.LiquidPint); - put(Units.DryPint, UnitConversionFactors.DryPint); - put(Units.LiquidQuart, UnitConversionFactors.LiquidQuart); - put(Units.DryQuart, UnitConversionFactors.DryQuart); - put(Units.LiquidGallon, UnitConversionFactors.LiquidGallon); - put(Units.DryGallon, UnitConversionFactors.DryGallon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Litre, UnitConversionFactors.Litre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Angle, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Radian, UnitConversionFactors.Radian); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Degree, UnitConversionFactors.Degree); - put(Units.Arcminute, UnitConversionFactors.Arcminute); - put(Units.Arcsecond, UnitConversionFactors.Arcsecond); - put(Units.Revolution, UnitConversionFactors.Revolution); - put(Units.Gradian, UnitConversionFactors.Gradian); - put(Units.Gon, UnitConversionFactors.Gon); - } - } - ); - } - } - ); - put - ( - UnitTypes.Information, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bit, UnitConversionFactors.Bit); - put(Units.Byte, UnitConversionFactors.Byte); - put(Units.Nibble, UnitConversionFactors.Nibble); - put(Units.Quartet, UnitConversionFactors.Quartet); - put(Units.Octet, UnitConversionFactors.Octet); - } - } - ); - } - } - ); - put - ( - UnitTypes.Force, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Newton, UnitConversionFactors.Newton); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.PoundForce, UnitConversionFactors.PoundForce); - put(Units.Poundal, UnitConversionFactors.Poundal); - put(Units.OunceForce, UnitConversionFactors.OunceForce); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Dyne, UnitConversionFactors.Dyne); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Kilopond, UnitConversionFactors.Kilopond); - put(Units.Kip, UnitConversionFactors.Kip); - } - } - ); - } - } - ); - put - ( - UnitTypes.Velocity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerSecond, UnitConversionFactors.MetrePerSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.CentimetrePerSecond, UnitConversionFactors.CentimetrePerSecond); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootPerSecond, UnitConversionFactors.FootPerSecond); - put(Units.InchPerSecond, UnitConversionFactors.InchPerSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Knot, UnitConversionFactors.Knot); - put(Units.KilometrePerHour, UnitConversionFactors.KilometrePerHour); - put(Units.MilePerHour, UnitConversionFactors.MilePerHour); - } - } - ); - } - } - ); - put - ( - UnitTypes.Acceleration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerSquareSecond, UnitConversionFactors.MetrePerSquareSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Gal, UnitConversionFactors.Gal); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootPerSquareSecond, UnitConversionFactors.FootPerSquareSecond); - put(Units.InchPerSquareSecond, UnitConversionFactors.InchPerSquareSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.Energy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Joule, UnitConversionFactors.Joule); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.BritishThermalUnit, UnitConversionFactors.BritishThermalUnit); - put(Units.ThermochemicalBritishThermalUnit, UnitConversionFactors.ThermochemicalBritishThermalUnit); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Erg, UnitConversionFactors.Erg); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Electronvolt, UnitConversionFactors.Electronvolt); - put(Units.WattHour, UnitConversionFactors.WattHour); - put(Units.Calorie, UnitConversionFactors.Calorie); - put(Units.ThermochemicalCalorie, UnitConversionFactors.ThermochemicalBritishThermalUnit); - put(Units.FoodCalorie, UnitConversionFactors.FoodCalorie); - put(Units.Therm, UnitConversionFactors.Therm); - put(Units.UKTherm, UnitConversionFactors.UKTherm); - put(Units.USTherm, UnitConversionFactors.USTherm); - } - } - ); - } - } - ); - put - ( - UnitTypes.Power, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Watt, UnitConversionFactors.Watt); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.ErgPerSecond, UnitConversionFactors.ErgPerSecond); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Horsepower, UnitConversionFactors.Horsepower); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.MetricHorsepower, UnitConversionFactors.MetricHorsepower); - put(Units.ElectricHorsepower, UnitConversionFactors.ElectricHorsepower); - put(Units.BoilerHorsepower, UnitConversionFactors.BoilerHorsepower); - put(Units.TonOfRefrigeration, UnitConversionFactors.TonOfRefrigeration); - } - } - ); - } - } - ); - put - ( - UnitTypes.Pressure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Pascal, UnitConversionFactors.Pascal); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Barye, UnitConversionFactors.Barye); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.PoundforcePerSquareInch, UnitConversionFactors.PoundforcePerSquareInch); - put(Units.PoundforcePerSquareFoot, UnitConversionFactors.PoundforcePerSquareFoot); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bar, UnitConversionFactors.Bar); - put(Units.Atmosphere, UnitConversionFactors.Atmosphere); - put(Units.TechnicalAtmosphere, UnitConversionFactors.TechnicalAtmosphere); - put(Units.MillimetreOfMercury, UnitConversionFactors.MillimetreOfMercury); - put(Units.InchOfMercury32F, UnitConversionFactors.InchOfMercury32F); - put(Units.InchOfMercury60F, UnitConversionFactors.InchOfMercury60F); - put(Units.Torr, UnitConversionFactors.Torr); - put(Units.KipPerSquareInch, UnitConversionFactors.KipPerSquareInch); - } - } - ); - } - } - ); - put - ( - UnitTypes.Frequency, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Hertz, UnitConversionFactors.Hertz); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.CyclePerSecond, UnitConversionFactors.CyclePerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCharge, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Coulomb, UnitConversionFactors.Coulomb); - put(Units.AmpereHour, UnitConversionFactors.AmpereHour); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Franklin, UnitConversionFactors.Franklin); - put(Units.Statcoulomb, UnitConversionFactors.Statcoulomb); - put(Units.ESUOfCharge, UnitConversionFactors.ESUOfCharge); - put(Units.Abcoulomb, UnitConversionFactors.Abcoulomb); - put(Units.EMUOfCharge, UnitConversionFactors.EMUOfCharge); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Ampere, UnitConversionFactors.Ampere); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statampere, UnitConversionFactors.Statampere); - put(Units.ESUOfCurrent, UnitConversionFactors.ESUOfCurrent); - put(Units.Abampere, UnitConversionFactors.Abampere); - put(Units.Biot, UnitConversionFactors.Biot); - put(Units.EMUOfCurrent, UnitConversionFactors.EMUOfCurrent); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricVoltage, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Volt, UnitConversionFactors.Volt); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statvolt, UnitConversionFactors.Statvolt); - put(Units.ESUOfElectricPotential, UnitConversionFactors.ESUOfElectricPotential); - put(Units.Abvolt, UnitConversionFactors.Abvolt); - put(Units.EMUOfElectricPotential, UnitConversionFactors.EMUOfElectricPotential); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricResistance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Ohm, UnitConversionFactors.Ohm); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statohm, UnitConversionFactors.Statohm); - put(Units.ESUOfResistance, UnitConversionFactors.ESUOfResistance); - put(Units.Abohm, UnitConversionFactors.Abohm); - put(Units.EMUOfResistance, UnitConversionFactors.EMUOfResistance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricResistivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.OhmMetre, UnitConversionFactors.OhmMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricConductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Siemens, UnitConversionFactors.Siemens); - put(Units.Mho, UnitConversionFactors.Mho); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statmho, UnitConversionFactors.Statmho); - put(Units.Statsiemens, UnitConversionFactors.Statsiemens); - put(Units.Abmho, UnitConversionFactors.Abmho); - put(Units.Absiemens, UnitConversionFactors.Absiemens); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Gemmho, UnitConversionFactors.Gemmho); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricConductivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SiemensPerMetre, UnitConversionFactors.SiemensPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCapacitance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Farad, UnitConversionFactors.Farad); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statfarad, UnitConversionFactors.Statfarad); - put(Units.ESUOfCapacitance, UnitConversionFactors.ESUOfCapacitance); - put(Units.Abfarad, UnitConversionFactors.Abfarad); - put(Units.EMUOfCapacitance, UnitConversionFactors.EMUOfCapacitance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricInductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Henry, UnitConversionFactors.Henry); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stathenry, UnitConversionFactors.Stathenry); - put(Units.ESUOfInductance, UnitConversionFactors.ESUOfInductance); - put(Units.Abhenry, UnitConversionFactors.Abhenry); - put(Units.EMUOfInductance, UnitConversionFactors.EMUOfInductance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricDipoleMoment, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombMetre, UnitConversionFactors.CoulombMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Debye, UnitConversionFactors.Debye); - } - } - ); - } - } - ); - put - ( - UnitTypes.Temperature, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - //Mere Placeholders. Temperature conversions are managed through a function. - put(Units.Kelvin, 1.0); - put(Units.DegreeCelsius, 1.0); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.DegreeFahrenheit, 1.0); - put(Units.DegreeRankine, 1.0); - } - } - ); - } - } - ); - put - ( - UnitTypes.Wavenumber, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.ReciprocalMetre, UnitConversionFactors.ReciprocalMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Kayser, UnitConversionFactors.Kayser); - } - } - ); - } - } - ); - put - ( - UnitTypes.Viscosity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.PascalSecond, UnitConversionFactors.PascalSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Poise, UnitConversionFactors.Poise); - } - } - ); - } - } - ); - put - ( - UnitTypes.KinematicViscosity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquareMetrePerSecond, UnitConversionFactors.SquareMetrePerSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stokes, UnitConversionFactors.Stokes); - } - } - ); - } - } - ); - put - ( - UnitTypes.AmountOfSubstance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Mole, UnitConversionFactors.Mole); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.PoundMole, UnitConversionFactors.PoundMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.Momentum, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonSecond, UnitConversionFactors.NewtonSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularVelocity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.RadianPerSecond, UnitConversionFactors.RadianPerSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.RevolutionPerMinute, UnitConversionFactors.RevolutionPerMinute); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularAcceleration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.RadianPerSquareSecond, UnitConversionFactors.RadianPerSquareSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularMomentum, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JouleSecond, UnitConversionFactors.JouleSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.MomentOfInertia, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramSquareMetre, UnitConversionFactors.KilogramSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SolidAngle, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Steradian, UnitConversionFactors.Steradian); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.SquareDegree, UnitConversionFactors.SquareDegree); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousIntensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Candela, UnitConversionFactors.Candela); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousFlux, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Lumen, UnitConversionFactors.Lumen); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousEnergy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.LumenSecond, UnitConversionFactors.LumenSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Talbot, UnitConversionFactors.Talbot); - } - } - ); - } - } - ); - put - ( - UnitTypes.Luminance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CandelaPerSquareMetre, UnitConversionFactors.CandelaPerSquareMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stilb, UnitConversionFactors.Stilb); - put(Units.Lambert, UnitConversionFactors.Lambert); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootLambert, UnitConversionFactors.FootLambert); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Nit, UnitConversionFactors.Nit); - } - } - ); - } - } - ); - put - ( - UnitTypes.Illuminance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Lux, UnitConversionFactors.Lux); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootCandle, UnitConversionFactors.FootCandle); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Phot, UnitConversionFactors.Phot); - } - } - ); - } - } - ); - put - ( - UnitTypes.Logarithmic, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bel, UnitConversionFactors.Bel); - put(Units.Neper, UnitConversionFactors.Neper); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFlux, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Weber, UnitConversionFactors.Weber); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Maxwell, UnitConversionFactors.Maxwell); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFieldB, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Tesla, UnitConversionFactors.Tesla); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Gauss, UnitConversionFactors.Gauss); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFieldH, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.AmperePerMetre, UnitConversionFactors.AmperePerMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Oersted, UnitConversionFactors.Oersted); - } - } - ); - } - } - ); - put - ( - UnitTypes.Radioactivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Becquerel, UnitConversionFactors.Becquerel); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Curie, UnitConversionFactors.Curie); - put(Units.DisintegrationsPerMinute, UnitConversionFactors.DisintegrationsPerMinute); - put(Units.DisintegrationsPerSecond, UnitConversionFactors.DisintegrationsPerSecond); - put(Units.Rutherford, UnitConversionFactors.Rutherford); - } - } - ); - } - } - ); - put - ( - UnitTypes.AbsorbedDose, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Gray, UnitConversionFactors.Gray); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Rad, UnitConversionFactors.Rad); - } - } - ); - } - } - ); - put - ( - UnitTypes.AbsorbedDoseRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.GrayPerSecond, UnitConversionFactors.GrayPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.EquivalentDose, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Sievert, UnitConversionFactors.Sievert); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.REM, UnitConversionFactors.REM); - } - } - ); - } - } - ); - put - ( - UnitTypes.Exposure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerKilogram, UnitConversionFactors.CoulombPerKilogram); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Roentgen, UnitConversionFactors.Roentgen); - } - } - ); - } - } - ); - put - ( - UnitTypes.CatalyticActivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Katal, UnitConversionFactors.Katal); - } - } - ); - } - } - ); - put - ( - UnitTypes.CatalyticActivityConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KatalPerCubicMetre, UnitConversionFactors.KatalPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Jerk, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerCubicSecond, UnitConversionFactors.MetrePerCubicSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.MassFlowRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerSecond, UnitConversionFactors.KilogramPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.Density, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerCubicMetre, UnitConversionFactors.KilogramPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.AreaDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerSquareMetre, UnitConversionFactors.KilogramPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.EnergyDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerCubicMetre, UnitConversionFactors.JoulePerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SpecificVolume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerKilogram, UnitConversionFactors.CubicMetrePerKilogram); - } - } - ); - } - } - ); - put - ( - UnitTypes.VolumetricFlowRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerSecond, UnitConversionFactors.CubicMetrePerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SurfaceTension, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerSquareMetre, UnitConversionFactors.JoulePerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SpecificWeight, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonPerCubicMetre, UnitConversionFactors.NewtonPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalConductivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerMetrePerKelvin, UnitConversionFactors.WattPerMetrePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalConductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerKelvin, UnitConversionFactors.WattPerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalResistivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetreKelvinPerWatt, UnitConversionFactors.MetreKelvinPerWatt); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalResistance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KelvinPerWatt, UnitConversionFactors.KelvinPerWatt); - } - } - ); - } - } - ); - put - ( - UnitTypes.HeatTransferCoefficient, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSquareMetrePerKelvin, UnitConversionFactors.WattPerSquareMetrePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.HeatFluxDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSquareMetre, UnitConversionFactors.WattPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Entropy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerKelvin, UnitConversionFactors.JoulePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricFieldStrength, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonPerCoulomb, UnitConversionFactors.NewtonPerCoulomb); - put(Units.VoltPerMetre, UnitConversionFactors.VoltPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.LinearElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerMetre, UnitConversionFactors.CoulombPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerSquareMetre, UnitConversionFactors.CoulombPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerCubicMetre, UnitConversionFactors.CoulombPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.CurrentDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.AmperePerSquareMetre, UnitConversionFactors.AmperePerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermittivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.FaradPerMetre, UnitConversionFactors.FaradPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermeability, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.HenryPerMetre, UnitConversionFactors.HenryPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarEnergy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerMole, UnitConversionFactors.JoulePerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarEntropy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerMolePerKelvin, UnitConversionFactors.JoulePerMolePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarVolume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerMole, UnitConversionFactors.CubicMetrePerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarMass, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerMole, UnitConversionFactors.KilogramPerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MolePerCubicMetre, UnitConversionFactors.MolePerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolalConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MolePerKilogram, UnitConversionFactors.MolePerKilogram); - } - } - ); - } - } - ); - put - ( - UnitTypes.RadiantIntensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSteradian, UnitConversionFactors.WattPerSteradian); - } - } - ); - } - } - ); - put - ( - UnitTypes.Radiance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSteradianPerSquareMetre, UnitConversionFactors.WattPerSteradianPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.FuelEconomy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.InverseSquareMetre, UnitConversionFactors.InverseSquareMetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.MilePerGallon, UnitConversionFactors.MilePerGallon); - put(Units.ImperialMilePerGallon, UnitConversionFactors.ImperialMilePerGallon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.USCSMilePerGallon, UnitConversionFactors.USCSMilePerGallon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.KilometrePerLitre, UnitConversionFactors.KilometrePerLitre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SoundExposure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquarePascalSecond, UnitConversionFactors.SquarePascalSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SoundImpedance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.PascalSecondPerCubicMetre, UnitConversionFactors.PascalSecondPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.RotationalStiffness, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonMetrePerRadian, UnitConversionFactors.NewtonMetrePerRadian); - } - } - ); - } - } - ); - put - ( - UnitTypes.BitRate, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.BitPerSecond, UnitConversionFactors.BitPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SymbolRate, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Baud, UnitConversionFactors.Baud); - } - } - ); - } - } - ); - } - }; - - AllBasicSystems = new HashMap() - { - { put(UnitSystems.SI, UnitSystems.SI); } - { put(UnitSystems.CGS, UnitSystems.CGS); } - { put(UnitSystems.Imperial, UnitSystems.Imperial); } - { put(UnitSystems.USCS, UnitSystems.Imperial); } - { put(UnitSystems.ImperialAndUSCS, UnitSystems.Imperial); } - { put(UnitSystems.None, UnitSystems.None); } - }; - - AllMetricEnglish = new HashMap() - { - { put(UnitSystems.SI, UnitSystems.SI); } - { put(UnitSystems.CGS, UnitSystems.SI); } - { put(UnitSystems.Imperial, UnitSystems.Imperial); } - { put(UnitSystems.USCS, UnitSystems.Imperial); } - { put(UnitSystems.ImperialAndUSCS, UnitSystems.Imperial); } - { put(UnitSystems.None, UnitSystems.None); } - }; - - DefaultUnnamedUnits = (HashMap)AllUnits.get(UnitTypes.None).entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - x.getValue(), new AbstractMap.SimpleEntry(Units.None, 0.0) - ) - .getKey() - ) - ); - - AllUnitTypes = MethodsHardcoding.GetAllMain(); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/65/d00897d0b34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/65/d00897d0b34a00171059ebc16969059f deleted file mode 100644 index 3b56357..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/65/d00897d0b34a00171059ebc16969059f +++ /dev/null @@ -1,1062 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - UnitInfo test = Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - System.out.println(test.Value); - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/0076676a414c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/0076676a414c00171eb8e3cba3fc21fa deleted file mode 100644 index ca8ce2a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/0076676a414c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,84 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //Emulating the conditions of the original C# version where decimal numbers cannot be parsed as integer. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - System.out.println(input + " " + output.IsOK); - - return output; - } - - static Number ParseCommon(String input) throws Exception - { - if - ( - input == null || Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(input.toLowerCase()), - x -> !Character.isDigit(x) && x != '.' && x != ',' && x != 'e', '\u0000' - ) - != '\u0000' - ) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - //Note that TryParseOutput analyses the exponential cases (i.e., including e + integer exponent) further. - throw new Exception(); - } - - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/3052beb7974a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/3052beb7974a00171930ee4d171ed0de deleted file mode 100644 index 0a079ac..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/3052beb7974a00171930ee4d171ed0de +++ /dev/null @@ -1,570 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - System.out.println(normalisedInfos.get(0).Value + " " + normalisedInfos.get(0).BaseTenExponent + " " + normalisedInfos.get(0).Prefix.Factor + " -- " + normalisedInfos.get(1).Value + " " + normalisedInfos.get(1).BaseTenExponent + " " + normalisedInfos.get(1).Prefix.Factor); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/807b8b3ef04c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/807b8b3ef04c00171048b3f61ecb42d3 deleted file mode 100644 index 4265bad..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/807b8b3ef04c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1209 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/80bc5517aa4a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/80bc5517aa4a00171059ebc16969059f deleted file mode 100644 index d062520..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/68/80bc5517aa4a00171059ebc16969059f +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/8035ff11ba4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/8035ff11ba4a0017160ae291ab4667e2 deleted file mode 100644 index 07c809e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/8035ff11ba4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/90cb0b8a994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/90cb0b8a994a00171930ee4d171ed0de deleted file mode 100644 index 774fd56..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/90cb0b8a994a00171930ee4d171ed0de +++ /dev/null @@ -1,135 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = - ( - improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - UnitInfo.Value - ); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/a0f67260c14a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/a0f67260c14a00171634abff01ee97d5 deleted file mode 100644 index 043d029..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/a0f67260c14a00171634abff01ee97d5 +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/f0574bbf294a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/f0574bbf294a001712d4a4f7b050cac8 deleted file mode 100644 index 45198a6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6b/f0574bbf294a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1384 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - System.out.println(parseInfo.InputToParse); - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6d/90e067512f4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6d/90e067512f4a001712d4a4f7b050cac8 deleted file mode 100644 index 886f724..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6d/90e067512f4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1865 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = unitInfo.Parts.OrderBy - ( - x => unitInfo.InitialPositions.First(y => y.Key == x).Value - ) - .ThenByDescending(x => x.Exponent).ToList(); - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6f/4050eca1994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6f/4050eca1994a00171930ee4d171ed0de deleted file mode 100644 index 68a3e72..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/6f/4050eca1994a00171930ee4d171ed0de +++ /dev/null @@ -1,136 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - System.out.println(UnitInfo.Value + " " + UnitInfo.BaseTenExponent + " " + UnitInfo.Prefix.Factor); - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = - ( - improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - UnitInfo.Value - ); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/70/404a5e88684c00171a25ec0b13e7f3ac b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/70/404a5e88684c00171a25ec0b13e7f3ac deleted file mode 100644 index 31c4349..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/70/404a5e88684c00171a25ec0b13e7f3ac +++ /dev/null @@ -1,220 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -import java.util.AbstractMap; - -/**Contains the main information associated with unit prefixes.**/ -public class Prefix implements Comparable -{ - /**Name of the unit prefix.**/ - public final String Name; - /**Symbol of the unit prefix.**/ - public final String Symbol; - /**Multiplying factor associated with the unit prefix.**/ - public final double Factor; - /**Type of the unit prefix.**/ - public final PrefixTypes Type; - /**Usage conditions of the unit prefix.**/ - public final PrefixUsageTypes PrefixUsage; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /**Initialises a new Prefix instance.**/ - public Prefix() - { - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - PrefixUsage = PrefixUsageTypes.DefaultUsage; - } - - /** - Initialises a new Prefix instance. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - } - - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor) - { - this(factor, PrefixUsageTypes.DefaultUsage); - } - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(factor, ""); - - if (Type != PrefixTypes.None) - { - Factor = factor; - Name = GetName(Type, Factor); - - Symbol = Linq.FirstOrDefaultDict - ( - Type == PrefixTypes.SI ? HCPrefixes.AllSIPrefixSymbols : - HCPrefixes.AllBinaryPrefixSymbols, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(null, 0.0) - ) - .getKey(); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol) - { - this(symbol, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(1.0, symbol); - - if (Type != PrefixTypes.None) - { - Symbol = symbol; - Factor = - ( - Type == PrefixTypes.SI ? - HCPrefixes.AllSIPrefixSymbols.get(symbol) : - HCPrefixes.AllBinaryPrefixSymbols.get(symbol) - ); - Name = GetName(Type, Factor); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name prefix Prefix variable whose information will be used. - **/ - public Prefix(Prefix prefix) - { - if (prefix == null) prefix = new Prefix(); - - Name = prefix.Name; - Symbol = prefix.Symbol; - Factor = prefix.Factor; - Type = prefix.Type; - PrefixUsage = prefix.PrefixUsage; - } - - static PrefixTypes GetType(double factor, String symbol) - { - PrefixTypes outType = PrefixTypes.None; - if (factor == 1.0 && symbol == "") return outType; - - if (factor != 1.0) - { - if (HCPrefixes.AllSIPrefixes.containsValue(factor)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixes.containsValue(factor)) - { - outType = PrefixTypes.Binary; - } - } - else - { - if (HCPrefixes.AllSIPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.Binary; - } - } - - return outType; - } - - static String GetName(PrefixTypes type, double factor) - { - return - ( - type == PrefixTypes.SI ? - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) : - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - ) - .getKey().toString(); - } - - @Override - ///Compares the current instance against another Prefix one. - ///The other Prefix instance. - public int compareTo(Prefix other) - { - return new Double(this.Factor).compareTo(other.Factor); - } - - @Override - ///Determines whether the current Prefix instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((Prefix)obj); - } - - boolean Equals(Prefix other) - { - return - ( - other == null ? false : - Equals.PrefixesAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this Prefix instance. - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/70/40aa809abc4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/70/40aa809abc4a0017160ae291ab4667e2 deleted file mode 100644 index 97fb50a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/70/40aa809abc4a0017160ae291ab4667e2 +++ /dev/null @@ -1,431 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - System.out.println(input); - if (input.toLowerCase().trim() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/70/d0929f25574c00171733ba4195e5d695 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/70/d0929f25574c00171733ba4195e5d695 deleted file mode 100644 index d66115b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/70/d0929f25574c00171733ba4195e5d695 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/71/809a4b3e7b4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/71/809a4b3e7b4c00171945f16efe0d9b5d deleted file mode 100644 index 715f1fa..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/71/809a4b3e7b4c00171945f16efe0d9b5d +++ /dev/null @@ -1,1378 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/71/c07b453a2f4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/71/c07b453a2f4a001712d4a4f7b050cac8 deleted file mode 100644 index d7c53d7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/71/c07b453a2f4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1859 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - System.out.println(unitInfo.Parts.get(0).Exponent); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/72/70095b952b4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/72/70095b952b4a001712d4a4f7b050cac8 deleted file mode 100644 index 42a269f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/72/70095b952b4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1164 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/72/80d2f371624c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/72/80d2f371624c0017146ede6da4ae5d42 deleted file mode 100644 index bff8a85..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/72/80d2f371624c0017146ede6da4ae5d42 +++ /dev/null @@ -1,29 +0,0 @@ -package test0; - -import java.util.ArrayList; -import java.util.Collections; - -import UnitParser.*; - -public class Main -{ - public static void main(String[] args) throws Exception - { - ArrayList tests = new ArrayList(); - tests.add(new Prefix(1000.0)); - tests.add(new Prefix(1000.0)); - tests.add(new Prefix(1000.0)); - - if(tests.get(0).equals(tests.get(2))) - { - System.out.println("Is OK"); - } - - Collections.sort(tests); - - for (Prefix item: tests) - { - System.out.println(item.Factor); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/72/f00a8b7e9a4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/72/f00a8b7e9a4a00171930ee4d171ed0de deleted file mode 100644 index b8a34d2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/72/f00a8b7e9a4a00171930ee4d171ed0de +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/73/4075e1176c4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/73/4075e1176c4c00171838d4a3813404a0 deleted file mode 100644 index a66bb72..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/73/4075e1176c4c00171838d4a3813404a0 +++ /dev/null @@ -1,302 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - X output = null; - try - { - output = GetFirst - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return output; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal, ExceptionTypes type) throws Exception - { - if (input == null) - { - return GetDefaultOrException(defaultVal, type); - } - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return GetDefaultOrException(defaultVal, type); - } - - private static X GetDefaultOrException(X defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - public static Map.Entry FirstDict(HashMap input) throws Exception - { - return FirstDict(input, null); - } - - public static Map.Entry FirstDict(HashMap input, Predicate> filter) throws Exception - { - if (filter != null) input = WhereDict(input, filter); - - return GetFirstDict - ( - input, filter, null, ExceptionTypes.FirstDict - ); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = input; - if (filter != null) - { - tempVar = WhereDict(input, filter); - } - if (tempVar == null) return defaultVal; - - HashMap input2 = new HashMap(tempVar); - - try - { - return GetFirstDict - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return defaultVal; - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal, ExceptionTypes type - ) - throws Exception - { - if (input == null) - { - return GetDefaultOrExceptionDict(defaultVal, type); - } - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return GetDefaultOrExceptionDict(defaultVal, type); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/74/f0905854294c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/74/f0905854294c00171ae7fcf2c321c986 deleted file mode 100644 index 4d19eed..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/74/f0905854294c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - System.out.println(tempInfo.Value + " " + tempInfo.BaseTenExponent); - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/75/f03374fb544c00171860ae6a5189088d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/75/f03374fb544c00171860ae6a5189088d deleted file mode 100644 index 4ec65c8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/75/f03374fb544c00171860ae6a5189088d +++ /dev/null @@ -1,12 +0,0 @@ -package test0; - -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP("5e1234"); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/76/60143b14bd4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/76/60143b14bd4a0017160ae291ab4667e2 deleted file mode 100644 index f64711f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/76/60143b14bd4a0017160ae291ab4667e2 +++ /dev/null @@ -1,429 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/76/60eade59f14c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/76/60eade59f14c00171048b3f61ecb42d3 deleted file mode 100644 index 51664f1..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/76/60eade59f14c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1210 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information associated with converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/78/40c05067b94a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/78/40c05067b94a0017160ae291ab4667e2 deleted file mode 100644 index 31216f2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/78/40c05067b94a0017160ae291ab4667e2 +++ /dev/null @@ -1,431 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.next(); - if (input.toLowerCase() == "y") - { - scanner.close(); - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - System.out.println("here"); - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/78/60a8c865b34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/78/60a8c865b34a00171059ebc16969059f deleted file mode 100644 index 391f7f7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/78/60a8c865b34a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/78/60d63a5ec04a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/78/60d63a5ec04a00171634abff01ee97d5 deleted file mode 100644 index 1589484..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/78/60d63a5ec04a00171634abff01ee97d5 +++ /dev/null @@ -1,240 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7a/00f0d4b3794c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7a/00f0d4b3794c00171945f16efe0d9b5d deleted file mode 100644 index 44bd9e9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7a/00f0d4b3794c00171945f16efe0d9b5d +++ /dev/null @@ -1,2634 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; - -import java.util.AbstractMap; -import java.util.HashMap; -import java.util.stream.Collectors; - - -/** -Class containing the main hardcoded resources which are used for internal purposes. -In the original C# code, all this is included in the file Keywords_Private_Main. - **/ -@SuppressWarnings("serial") -public class HCMain -{ - //Main classification for all the units (type, system and conversion factor). - //This dictionary represents an easily-modifiable container of well-structured unit information. - //After using all this information to create more specific/efficient collections, GetAllMain() deletes it. - public static HashMap>> AllUnits; - - /** - HashMap mostly meant to deal with the Imperial/USCS peculiar relationship. - **/ - public static HashMap AllBasicSystems; - - /** - Some times, all what matters is knowing whether the system is metric (SI/CGS) or English (Imperial/USCS). - **/ - public static HashMap AllMetricEnglish; - - /** - This collection relates all the unnamed units with their associated systems. - There are many units which don't fit any Units enum case, the unnamed units. - Unnamed units avoid a huge (and not too logical) hardcoding effort. - Note that UnitParser supports much more units than just the members of the Units enum. - By bearing in mind that any combination of named units forming a supported type is also - supported, the total number of supported units is way too big to even think about facing - it in a hardcoding-all-of-them way. - **/ - public static HashMap DefaultUnnamedUnits; - - /** - Relates all the units with their respective types. - The call to GetALLMain() also populates all the collections below this line. - **/ - public static HashMap AllUnitTypes; - - /**Relates all the units with their respective systems.**/ - public static HashMap AllUnitSystems; - - /**Relates all the units with their respective conversion factors.**/ - public static HashMap AllUnitConversionFactors; - - /**Includes all the supported unit string representations (case doesn't matter).**/ - public static HashMap AllUnitStrings; - - /**Includes secondary symbols for some units (case does matter).**/ - public static HashMap AllUnitSymbols2; - - /**Some conversion factors are too small/big for the decimal type.**/ - public static HashMap AllBeyondDecimalConversionFactors; - - public static void Start() - { - AllUnits = new HashMap>>() - { - { - put - ( - UnitTypes.None, - new HashMap>() - { - { - put - ( - UnitSystems.SI, new HashMap() - { - { put(Units.ValidSIUnit, 1.0); } - } - ); - put - ( - UnitSystems.Imperial, new HashMap() - { - { put(Units.ValidImperialUSCSUnit, 1.0); put(Units.ValidImperialUnit, 1.0); } - } - ); - put - ( - UnitSystems.USCS, new HashMap() - { - { put(Units.ValidUSCSUnit, 1.0); } - } - ); - put - ( - UnitSystems.CGS, new HashMap() - { - { put(Units.ValidCGSUnit, 1.0); } - } - ); - put - ( - UnitSystems.None, new HashMap() - { - { put(Units.ValidUnit, 1.0); put(Units.Unitless, 1.0); } - } - ); - } - } - ); - put - ( - UnitTypes.Length, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Metre, UnitConversionFactors.Metre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Centimetre, UnitConversionFactors.Centimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Foot, UnitConversionFactors.Foot); - put(Units.Thou, UnitConversionFactors.Thou); - put(Units.Mil, UnitConversionFactors.Mil); - put(Units.Inch, UnitConversionFactors.Inch); - put(Units.Yard, UnitConversionFactors.Yard); - put(Units.Fathom, UnitConversionFactors.Fathom); - put(Units.Rod, UnitConversionFactors.Rod); - put(Units.Perch, UnitConversionFactors.Perch); - put(Units.Pole, UnitConversionFactors.Pole); - put(Units.Chain, UnitConversionFactors.Chain); - put(Units.Furlong, UnitConversionFactors.Furlong); - put(Units.Mile, UnitConversionFactors.Mile); - put(Units.Link, UnitConversionFactors.Link); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.SurveyInch, UnitConversionFactors.SurveyInch); - put(Units.SurveyFoot, UnitConversionFactors.SurveyFoot); - put(Units.SurveyYard, UnitConversionFactors.SurveyYard); - put(Units.SurveyRod, UnitConversionFactors.SurveyRod); - put(Units.SurveyChain, UnitConversionFactors.SurveyChain); - put(Units.SurveyLink, UnitConversionFactors.SurveyLink); - put(Units.SurveyMile, UnitConversionFactors.SurveyMile); - put(Units.SurveyFathom, UnitConversionFactors.SurveyFathom); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.AstronomicalUnit, UnitConversionFactors.AstronomicalUnit); - put(Units.NauticalMile, UnitConversionFactors.NauticalMile); - put(Units.Angstrom, UnitConversionFactors.Angstrom); - put(Units.Fermi, UnitConversionFactors.Fermi); - put(Units.LightYear, UnitConversionFactors.LightYear); - put(Units.Parsec, UnitConversionFactors.Parsec); - put(Units.Micron, UnitConversionFactors.Micron); - } - } - ); - } - } - ); - put - ( - UnitTypes.Mass, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Gram, UnitConversionFactors.Gram); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Pound, UnitConversionFactors.Pound); - put(Units.Grain, UnitConversionFactors.Grain); - put(Units.Drachm, UnitConversionFactors.Drachm); - put(Units.Ounce, UnitConversionFactors.Ounce); - put(Units.Stone, UnitConversionFactors.Stone); - put(Units.Slug, UnitConversionFactors.Slug); - put(Units.Quarter, UnitConversionFactors.Quarter); - put(Units.LongQuarter, UnitConversionFactors.LongQuarter); - put(Units.Hundredweight, UnitConversionFactors.Hundredweight); - put(Units.LongHundredweight, UnitConversionFactors.LongHundredweight); - put(Units.Ton, UnitConversionFactors.Ton); - put(Units.LongTon, UnitConversionFactors.LongTon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.ShortQuarter, UnitConversionFactors.ShortQuarter); - put(Units.ShortHundredweight, UnitConversionFactors.ShortHundredweight); - put(Units.ShortTon, UnitConversionFactors.ShortTon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.MetricTon, UnitConversionFactors.MetricTon); - put(Units.Dalton, UnitConversionFactors.Dalton); - put(Units.UnifiedAtomicMassUnit, UnitConversionFactors.UnifiedAtomicMassUnit); - put(Units.Carat, UnitConversionFactors.Carat); - } - } - ); - } - } - ); - put - ( - UnitTypes.Time, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Second, UnitConversionFactors.Second); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Minute, UnitConversionFactors.Minute); - put(Units.Hour, UnitConversionFactors.Hour); - put(Units.Day, UnitConversionFactors.Day); - put(Units.Shake, UnitConversionFactors.Shake); - } - } - ); - } - } - ); - put - ( - UnitTypes.Area, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquareMetre, UnitConversionFactors.SquareMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.SquareCentimetre, UnitConversionFactors.SquareCentimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.SquareFoot, UnitConversionFactors.SquareFoot); - put(Units.SquareInch, UnitConversionFactors.SquareInch); - put(Units.SquareRod, UnitConversionFactors.SquareRod); - put(Units.SquarePerch, UnitConversionFactors.SquarePerch); - put(Units.SquarePole, UnitConversionFactors.SquarePole); - put(Units.Rood, UnitConversionFactors.Rood); - put(Units.Acre, UnitConversionFactors.Acre); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.SurveyAcre, UnitConversionFactors.SurveyAcre); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Are, UnitConversionFactors.Are); - put(Units.Barn, UnitConversionFactors.Barn); - } - } - ); - } - } - ); - put - ( - UnitTypes.Volume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetre, UnitConversionFactors.CubicMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.CubicCentimetre, UnitConversionFactors.CubicCentimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.CubicFoot, UnitConversionFactors.CubicFoot); - put(Units.CubicInch, UnitConversionFactors.CubicInch); - put(Units.FluidOunce, UnitConversionFactors.FluidOunce); - put(Units.ImperialFluidOunce, UnitConversionFactors.ImperialFluidOunce); - put(Units.Gill, UnitConversionFactors.Gill); - put(Units.ImperialGill, UnitConversionFactors.ImperialGill); - put(Units.Pint, UnitConversionFactors.Pint); - put(Units.ImperialPint, UnitConversionFactors.ImperialPint); - put(Units.Quart, UnitConversionFactors.Quart); - put(Units.ImperialQuart, UnitConversionFactors.ImperialQuart); - put(Units.Gallon, UnitConversionFactors.Gallon); - put(Units.ImperialGallon, UnitConversionFactors.ImperialGallon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.USCSFluidOunce, UnitConversionFactors.USCSFluidOunce); - put(Units.USCSGill, UnitConversionFactors.USCSGill); - put(Units.LiquidPint, UnitConversionFactors.LiquidPint); - put(Units.DryPint, UnitConversionFactors.DryPint); - put(Units.LiquidQuart, UnitConversionFactors.LiquidQuart); - put(Units.DryQuart, UnitConversionFactors.DryQuart); - put(Units.LiquidGallon, UnitConversionFactors.LiquidGallon); - put(Units.DryGallon, UnitConversionFactors.DryGallon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Litre, UnitConversionFactors.Litre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Angle, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Radian, UnitConversionFactors.Radian); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Degree, UnitConversionFactors.Degree); - put(Units.Arcminute, UnitConversionFactors.Arcminute); - put(Units.Arcsecond, UnitConversionFactors.Arcsecond); - put(Units.Revolution, UnitConversionFactors.Revolution); - put(Units.Gradian, UnitConversionFactors.Gradian); - put(Units.Gon, UnitConversionFactors.Gon); - } - } - ); - } - } - ); - put - ( - UnitTypes.Information, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bit, UnitConversionFactors.Bit); - put(Units.Byte, UnitConversionFactors.Byte); - put(Units.Nibble, UnitConversionFactors.Nibble); - put(Units.Quartet, UnitConversionFactors.Quartet); - put(Units.Octet, UnitConversionFactors.Octet); - } - } - ); - } - } - ); - put - ( - UnitTypes.Force, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Newton, UnitConversionFactors.Newton); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.PoundForce, UnitConversionFactors.PoundForce); - put(Units.Poundal, UnitConversionFactors.Poundal); - put(Units.OunceForce, UnitConversionFactors.OunceForce); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Dyne, UnitConversionFactors.Dyne); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Kilopond, UnitConversionFactors.Kilopond); - put(Units.Kip, UnitConversionFactors.Kip); - } - } - ); - } - } - ); - put - ( - UnitTypes.Velocity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerSecond, UnitConversionFactors.MetrePerSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.CentimetrePerSecond, UnitConversionFactors.CentimetrePerSecond); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootPerSecond, UnitConversionFactors.FootPerSecond); - put(Units.InchPerSecond, UnitConversionFactors.InchPerSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Knot, UnitConversionFactors.Knot); - put(Units.KilometrePerHour, UnitConversionFactors.KilometrePerHour); - put(Units.MilePerHour, UnitConversionFactors.MilePerHour); - } - } - ); - } - } - ); - put - ( - UnitTypes.Acceleration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerSquareSecond, UnitConversionFactors.MetrePerSquareSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Gal, UnitConversionFactors.Gal); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootPerSquareSecond, UnitConversionFactors.FootPerSquareSecond); - put(Units.InchPerSquareSecond, UnitConversionFactors.InchPerSquareSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.Energy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Joule, UnitConversionFactors.Joule); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.BritishThermalUnit, UnitConversionFactors.BritishThermalUnit); - put(Units.ThermochemicalBritishThermalUnit, UnitConversionFactors.ThermochemicalBritishThermalUnit); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Erg, UnitConversionFactors.Erg); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Electronvolt, UnitConversionFactors.Electronvolt); - put(Units.WattHour, UnitConversionFactors.WattHour); - put(Units.Calorie, UnitConversionFactors.Calorie); - put(Units.ThermochemicalCalorie, UnitConversionFactors.ThermochemicalBritishThermalUnit); - put(Units.FoodCalorie, UnitConversionFactors.FoodCalorie); - put(Units.Therm, UnitConversionFactors.Therm); - put(Units.UKTherm, UnitConversionFactors.UKTherm); - put(Units.USTherm, UnitConversionFactors.USTherm); - } - } - ); - } - } - ); - put - ( - UnitTypes.Power, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Watt, UnitConversionFactors.Watt); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.ErgPerSecond, UnitConversionFactors.ErgPerSecond); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Horsepower, UnitConversionFactors.Horsepower); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.MetricHorsepower, UnitConversionFactors.MetricHorsepower); - put(Units.ElectricHorsepower, UnitConversionFactors.ElectricHorsepower); - put(Units.BoilerHorsepower, UnitConversionFactors.BoilerHorsepower); - put(Units.TonOfRefrigeration, UnitConversionFactors.TonOfRefrigeration); - } - } - ); - } - } - ); - put - ( - UnitTypes.Pressure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Pascal, UnitConversionFactors.Pascal); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Barye, UnitConversionFactors.Barye); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.PoundforcePerSquareInch, UnitConversionFactors.PoundforcePerSquareInch); - put(Units.PoundforcePerSquareFoot, UnitConversionFactors.PoundforcePerSquareFoot); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bar, UnitConversionFactors.Bar); - put(Units.Atmosphere, UnitConversionFactors.Atmosphere); - put(Units.TechnicalAtmosphere, UnitConversionFactors.TechnicalAtmosphere); - put(Units.MillimetreOfMercury, UnitConversionFactors.MillimetreOfMercury); - put(Units.InchOfMercury32F, UnitConversionFactors.InchOfMercury32F); - put(Units.InchOfMercury60F, UnitConversionFactors.InchOfMercury60F); - put(Units.Torr, UnitConversionFactors.Torr); - put(Units.KipPerSquareInch, UnitConversionFactors.KipPerSquareInch); - } - } - ); - } - } - ); - put - ( - UnitTypes.Frequency, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Hertz, UnitConversionFactors.Hertz); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.CyclePerSecond, UnitConversionFactors.CyclePerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCharge, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Coulomb, UnitConversionFactors.Coulomb); - put(Units.AmpereHour, UnitConversionFactors.AmpereHour); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Franklin, UnitConversionFactors.Franklin); - put(Units.Statcoulomb, UnitConversionFactors.Statcoulomb); - put(Units.ESUOfCharge, UnitConversionFactors.ESUOfCharge); - put(Units.Abcoulomb, UnitConversionFactors.Abcoulomb); - put(Units.EMUOfCharge, UnitConversionFactors.EMUOfCharge); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Ampere, UnitConversionFactors.Ampere); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statampere, UnitConversionFactors.Statampere); - put(Units.ESUOfCurrent, UnitConversionFactors.ESUOfCurrent); - put(Units.Abampere, UnitConversionFactors.Abampere); - put(Units.Biot, UnitConversionFactors.Biot); - put(Units.EMUOfCurrent, UnitConversionFactors.EMUOfCurrent); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricVoltage, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Volt, UnitConversionFactors.Volt); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statvolt, UnitConversionFactors.Statvolt); - put(Units.ESUOfElectricPotential, UnitConversionFactors.ESUOfElectricPotential); - put(Units.Abvolt, UnitConversionFactors.Abvolt); - put(Units.EMUOfElectricPotential, UnitConversionFactors.EMUOfElectricPotential); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricResistance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Ohm, UnitConversionFactors.Ohm); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statohm, UnitConversionFactors.Statohm); - put(Units.ESUOfResistance, UnitConversionFactors.ESUOfResistance); - put(Units.Abohm, UnitConversionFactors.Abohm); - put(Units.EMUOfResistance, UnitConversionFactors.EMUOfResistance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricResistivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.OhmMetre, UnitConversionFactors.OhmMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricConductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Siemens, UnitConversionFactors.Siemens); - put(Units.Mho, UnitConversionFactors.Mho); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statmho, UnitConversionFactors.Statmho); - put(Units.Statsiemens, UnitConversionFactors.Statsiemens); - put(Units.Abmho, UnitConversionFactors.Abmho); - put(Units.Absiemens, UnitConversionFactors.Absiemens); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Gemmho, UnitConversionFactors.Gemmho); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricConductivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SiemensPerMetre, UnitConversionFactors.SiemensPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCapacitance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Farad, UnitConversionFactors.Farad); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statfarad, UnitConversionFactors.Statfarad); - put(Units.ESUOfCapacitance, UnitConversionFactors.ESUOfCapacitance); - put(Units.Abfarad, UnitConversionFactors.Abfarad); - put(Units.EMUOfCapacitance, UnitConversionFactors.EMUOfCapacitance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricInductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Henry, UnitConversionFactors.Henry); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stathenry, UnitConversionFactors.Stathenry); - put(Units.ESUOfInductance, UnitConversionFactors.ESUOfInductance); - put(Units.Abhenry, UnitConversionFactors.Abhenry); - put(Units.EMUOfInductance, UnitConversionFactors.EMUOfInductance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricDipoleMoment, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombMetre, UnitConversionFactors.CoulombMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Debye, UnitConversionFactors.Debye); - } - } - ); - } - } - ); - put - ( - UnitTypes.Temperature, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - //Mere Placeholders. Temperature conversions are managed through a function. - put(Units.Kelvin, 1.0); - put(Units.DegreeCelsius, 1.0); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.DegreeFahrenheit, 1.0); - put(Units.DegreeRankine, 1.0); - } - } - ); - } - } - ); - put - ( - UnitTypes.Wavenumber, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.ReciprocalMetre, UnitConversionFactors.ReciprocalMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Kayser, UnitConversionFactors.Kayser); - } - } - ); - } - } - ); - put - ( - UnitTypes.Viscosity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.PascalSecond, UnitConversionFactors.PascalSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Poise, UnitConversionFactors.Poise); - } - } - ); - } - } - ); - put - ( - UnitTypes.KinematicViscosity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquareMetrePerSecond, UnitConversionFactors.SquareMetrePerSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stokes, UnitConversionFactors.Stokes); - } - } - ); - } - } - ); - put - ( - UnitTypes.AmountOfSubstance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Mole, UnitConversionFactors.Mole); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.PoundMole, UnitConversionFactors.PoundMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.Momentum, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonSecond, UnitConversionFactors.NewtonSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularVelocity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.RadianPerSecond, UnitConversionFactors.RadianPerSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.RevolutionPerMinute, UnitConversionFactors.RevolutionPerMinute); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularAcceleration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.RadianPerSquareSecond, UnitConversionFactors.RadianPerSquareSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularMomentum, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JouleSecond, UnitConversionFactors.JouleSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.MomentOfInertia, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramSquareMetre, UnitConversionFactors.KilogramSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SolidAngle, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Steradian, UnitConversionFactors.Steradian); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.SquareDegree, UnitConversionFactors.SquareDegree); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousIntensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Candela, UnitConversionFactors.Candela); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousFlux, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Lumen, UnitConversionFactors.Lumen); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousEnergy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.LumenSecond, UnitConversionFactors.LumenSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Talbot, UnitConversionFactors.Talbot); - } - } - ); - } - } - ); - put - ( - UnitTypes.Luminance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CandelaPerSquareMetre, UnitConversionFactors.CandelaPerSquareMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stilb, UnitConversionFactors.Stilb); - put(Units.Lambert, UnitConversionFactors.Lambert); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootLambert, UnitConversionFactors.FootLambert); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Nit, UnitConversionFactors.Nit); - } - } - ); - } - } - ); - put - ( - UnitTypes.Illuminance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Lux, UnitConversionFactors.Lux); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootCandle, UnitConversionFactors.FootCandle); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Phot, UnitConversionFactors.Phot); - } - } - ); - } - } - ); - put - ( - UnitTypes.Logarithmic, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bel, UnitConversionFactors.Bel); - put(Units.Neper, UnitConversionFactors.Neper); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFlux, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Weber, UnitConversionFactors.Weber); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Maxwell, UnitConversionFactors.Maxwell); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFieldB, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Tesla, UnitConversionFactors.Tesla); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Gauss, UnitConversionFactors.Gauss); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFieldH, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.AmperePerMetre, UnitConversionFactors.AmperePerMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Oersted, UnitConversionFactors.Oersted); - } - } - ); - } - } - ); - put - ( - UnitTypes.Radioactivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Becquerel, UnitConversionFactors.Becquerel); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Curie, UnitConversionFactors.Curie); - put(Units.DisintegrationsPerMinute, UnitConversionFactors.DisintegrationsPerMinute); - put(Units.DisintegrationsPerSecond, UnitConversionFactors.DisintegrationsPerSecond); - put(Units.Rutherford, UnitConversionFactors.Rutherford); - } - } - ); - } - } - ); - put - ( - UnitTypes.AbsorbedDose, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Gray, UnitConversionFactors.Gray); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Rad, UnitConversionFactors.Rad); - } - } - ); - } - } - ); - put - ( - UnitTypes.AbsorbedDoseRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.GrayPerSecond, UnitConversionFactors.GrayPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.EquivalentDose, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Sievert, UnitConversionFactors.Sievert); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.REM, UnitConversionFactors.REM); - } - } - ); - } - } - ); - put - ( - UnitTypes.Exposure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerKilogram, UnitConversionFactors.CoulombPerKilogram); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Roentgen, UnitConversionFactors.Roentgen); - } - } - ); - } - } - ); - put - ( - UnitTypes.CatalyticActivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Katal, UnitConversionFactors.Katal); - } - } - ); - } - } - ); - put - ( - UnitTypes.CatalyticActivityConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KatalPerCubicMetre, UnitConversionFactors.KatalPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Jerk, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerCubicSecond, UnitConversionFactors.MetrePerCubicSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.MassFlowRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerSecond, UnitConversionFactors.KilogramPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.Density, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerCubicMetre, UnitConversionFactors.KilogramPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.AreaDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerSquareMetre, UnitConversionFactors.KilogramPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.EnergyDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerCubicMetre, UnitConversionFactors.JoulePerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SpecificVolume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerKilogram, UnitConversionFactors.CubicMetrePerKilogram); - } - } - ); - } - } - ); - put - ( - UnitTypes.VolumetricFlowRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerSecond, UnitConversionFactors.CubicMetrePerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SurfaceTension, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerSquareMetre, UnitConversionFactors.JoulePerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SpecificWeight, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonPerCubicMetre, UnitConversionFactors.NewtonPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalConductivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerMetrePerKelvin, UnitConversionFactors.WattPerMetrePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalConductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerKelvin, UnitConversionFactors.WattPerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalResistivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetreKelvinPerWatt, UnitConversionFactors.MetreKelvinPerWatt); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalResistance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KelvinPerWatt, UnitConversionFactors.KelvinPerWatt); - } - } - ); - } - } - ); - put - ( - UnitTypes.HeatTransferCoefficient, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSquareMetrePerKelvin, UnitConversionFactors.WattPerSquareMetrePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.HeatFluxDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSquareMetre, UnitConversionFactors.WattPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Entropy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerKelvin, UnitConversionFactors.JoulePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricFieldStrength, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonPerCoulomb, UnitConversionFactors.NewtonPerCoulomb); - put(Units.VoltPerMetre, UnitConversionFactors.VoltPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.LinearElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerMetre, UnitConversionFactors.CoulombPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerSquareMetre, UnitConversionFactors.CoulombPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerCubicMetre, UnitConversionFactors.CoulombPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.CurrentDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.AmperePerSquareMetre, UnitConversionFactors.AmperePerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermittivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.FaradPerMetre, UnitConversionFactors.FaradPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermeability, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.HenryPerMetre, UnitConversionFactors.HenryPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarEnergy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerMole, UnitConversionFactors.JoulePerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarEntropy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerMolePerKelvin, UnitConversionFactors.JoulePerMolePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarVolume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerMole, UnitConversionFactors.CubicMetrePerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarMass, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerMole, UnitConversionFactors.KilogramPerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MolePerCubicMetre, UnitConversionFactors.MolePerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolalConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MolePerKilogram, UnitConversionFactors.MolePerKilogram); - } - } - ); - } - } - ); - put - ( - UnitTypes.RadiantIntensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSteradian, UnitConversionFactors.WattPerSteradian); - } - } - ); - } - } - ); - put - ( - UnitTypes.Radiance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSteradianPerSquareMetre, UnitConversionFactors.WattPerSteradianPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.FuelEconomy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.InverseSquareMetre, UnitConversionFactors.InverseSquareMetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.MilePerGallon, UnitConversionFactors.MilePerGallon); - put(Units.ImperialMilePerGallon, UnitConversionFactors.ImperialMilePerGallon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.USCSMilePerGallon, UnitConversionFactors.USCSMilePerGallon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.KilometrePerLitre, UnitConversionFactors.KilometrePerLitre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SoundExposure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquarePascalSecond, UnitConversionFactors.SquarePascalSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SoundImpedance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.PascalSecondPerCubicMetre, UnitConversionFactors.PascalSecondPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.RotationalStiffness, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonMetrePerRadian, UnitConversionFactors.NewtonMetrePerRadian); - } - } - ); - } - } - ); - put - ( - UnitTypes.BitRate, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.BitPerSecond, UnitConversionFactors.BitPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SymbolRate, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Baud, UnitConversionFactors.Baud); - } - } - ); - } - } - ); - } - }; - - AllBasicSystems = new HashMap() - { - { put(UnitSystems.SI, UnitSystems.SI); } - { put(UnitSystems.CGS, UnitSystems.CGS); } - { put(UnitSystems.Imperial, UnitSystems.Imperial); } - { put(UnitSystems.USCS, UnitSystems.Imperial); } - { put(UnitSystems.ImperialAndUSCS, UnitSystems.Imperial); } - { put(UnitSystems.None, UnitSystems.None); } - }; - - AllMetricEnglish = new HashMap() - { - { put(UnitSystems.SI, UnitSystems.SI); } - { put(UnitSystems.CGS, UnitSystems.SI); } - { put(UnitSystems.Imperial, UnitSystems.Imperial); } - { put(UnitSystems.USCS, UnitSystems.Imperial); } - { put(UnitSystems.ImperialAndUSCS, UnitSystems.Imperial); } - { put(UnitSystems.None, UnitSystems.None); } - }; - - DefaultUnnamedUnits = (HashMap)AllUnits.get(UnitTypes.None).entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - x.getValue(), new AbstractMap.SimpleEntry(Units.None, 0.0) - ) - .getKey() - ) - ); - - AllUnitTypes = MethodsHardcoding.GetAllMain(); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7a/4056ce12c34a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7a/4056ce12c34a00171634abff01ee97d5 deleted file mode 100644 index 9b35ab5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7a/4056ce12c34a00171634abff01ee97d5 +++ /dev/null @@ -1,20 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits); - - //UnitP test = UnitP.Division - //( - // new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - // new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - //); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7a/d07659eeaf4b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7a/d07659eeaf4b00171c69d98bf667dda6 deleted file mode 100644 index e5d4edd..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7a/d07659eeaf4b00171c69d98bf667dda6 +++ /dev/null @@ -1,1032 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/306dfba96e4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/306dfba96e4c00171838d4a3813404a0 deleted file mode 100644 index 1d3e77e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/306dfba96e4c00171838d4a3813404a0 +++ /dev/null @@ -1,252 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || filter == null) return new ArrayList(); - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), filter, defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/50b33c1e624c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/50b33c1e624c0017146ede6da4ae5d42 deleted file mode 100644 index 0cb9379..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/50b33c1e624c0017146ede6da4ae5d42 +++ /dev/null @@ -1,165 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return - ( - first.Error.equals(second.Error) - ); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type == ErrorTypes.None || secondInfo.Error.Type == ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling == second.ExceptionHandling && - first.Type == second.Type - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/70f1ee317f4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/70f1ee317f4c00171945f16efe0d9b5d deleted file mode 100644 index f3413a6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/70f1ee317f4c00171945f16efe0d9b5d +++ /dev/null @@ -1,107 +0,0 @@ -package InternalUnitParser.Operations; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class OperationsOther -{ - public static String GetOperationString(UnitP first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(UnitP first, Double second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), second.toString(), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(Double first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - first.toString(), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - private static String GetUnitPString(UnitP unitP) - { - return unitP.OriginalUnitString; - } - - private static String ConcatenateOperationString(String first, String second, char operation) - { - return (first + " " + operation + " " + second); - } - - //NOTE: the order within each char[] collection does matter. The first element will be treated as the default - //symbol for the given operation (e.g., used when creating a String including that operation). - public static HashMap> OperationSymbols; - - public static ArrayList UnitParseIgnored; - - public static final double MaxValue = 79228162514264337593543950335.0; //C# Decimal.MaxValue actual value. - public static final double MinValue = 0.0000000000000000000000000001; //C# Decimal precision lowest limit. - - public static String Start() - { - ArrayList UnitParseIgnored0 = new ArrayList() - {{ - add("/"); add("∕"); add("â„"); add("÷"); add("|"); add("\\"); - }}; - - OperationSymbols = new HashMap>() - { - { - { - put - ( - Operations.Addition, new ArrayList() - {{ - add('+'); - }} - ); - put - ( - Operations.Subtraction, new ArrayList() - {{ - add('-'); add('−'); add('—'); - }} - ); - put - ( - Operations.Multiplication, new ArrayList() - {{ - add('*'); add('x'); add('X'); add('×'); add('⊗'); add('â‹…'); add('·'); - }} - ); - put - ( - Operations.Division, new ArrayList() - {{ - add('/'); add('â„'); add('÷'); - //add('/'); add('∕'); add('â„'); add('÷'); add('|'); add('\\'); - }} - ); - } - } - }; - - UnitParseIgnored = new ArrayList() - {{ - add("."); add(","); add(":"); add(";"); add("_"); add("^"); add("+"); - add("#"); add("("); add(")"); add("["); add("]"); add("{"); add("}"); - add("="); add("!"); add("?"); add("@"); add("&"); - }}; - - return ""; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/80a2bf6f644c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/80a2bf6f644c0017146ede6da4ae5d42 deleted file mode 100644 index 6f8a53f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7b/80a2bf6f644c0017146ede6da4ae5d42 +++ /dev/null @@ -1,437 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type.equals(UnitP.ErrorTypes.None)) - { - System.out.println("Condition 4 true"); - //This condition is true. - } - if (!new UnitP("wrong").Error.Type.equals(UnitP.ErrorTypes.None)) - { - System.out.println("Condition 5 true"); - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7c/5042a4ab994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7c/5042a4ab994a00171930ee4d171ed0de deleted file mode 100644 index 4ade0e3..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7c/5042a4ab994a00171930ee4d171ed0de +++ /dev/null @@ -1,137 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - //System.out.println(UnitInfo.Value + " " + UnitInfo.BaseTenExponent + " " + UnitInfo.Prefix.Factor); - System.out.println("asfasdf"); - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = - ( - improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - UnitInfo.Value - ); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7c/90a5a773794c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7c/90a5a773794c00171945f16efe0d9b5d deleted file mode 100644 index 90d75bc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7c/90a5a773794c00171945f16efe0d9b5d +++ /dev/null @@ -1,147 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -import java.util.ArrayList; - -//Class storing all -public class CSharpOther -{ - public static String StartHarcoding() - { - HCPrefixes.Start(); - HCUnits.Start(); - HCMain.Start(); - HCCompounds.Start(); - HCOther.Start(); - OperationsOther.Start(); - - return ""; - } - - public static String[] SplitTryCatch(String input, String separator) - { - String[] output = new String[] { input }; - - if (input == null || separator == null) return output; - - try - { - output = input.split(separator); - } - catch(Exception e) { } - - return output; - } - - public static ArrayList StringToCharacters(String input) - { - ArrayList chars = new ArrayList(); - if (input == null) return chars; - - for (char item: input.toCharArray()) - { - chars.add(item); - } - - return chars; - } - - public static ArrayList ArrayToArrayList(X[] input) - { - ArrayList output = new ArrayList(); - - for (X item: input) - { - output.add(item); - } - - return output; - } - - public static String StringJoin(String separator, String[] parts, int start, int length) - { - return StringJoin - ( - separator, ArrayToArrayList(parts), start, length - ); - } - - public static String StringJoin(String separator, String[] parts) - { - return StringJoin - ( - separator, ArrayToArrayList(parts) - ); - } - - public static String StringJoin(String separator, ArrayList parts) - { - return StringJoinInternal - ( - separator, parts, null, 0, parts.size() - ); - } - - public static String StringJoin(String separator, ArrayList parts, int start, int length) - { - return StringJoinInternal - ( - separator, parts, null, start, length - ); - } - - public static String StringJoinChars(String separator, ArrayList parts2) - { - return StringJoinInternal - ( - separator, null, parts2, 0, (parts2 == null ? 0 : parts2.size()) - ); - } - - static String StringJoinInternal(String separator, ArrayList parts, ArrayList parts2, int start, int length) - { - if (parts == null && parts2 == null) return null; - - int total = - ( - parts == null ? parts2.size() : parts.size() - ); - if (total == 1) - { - return - ( - parts == null ? parts2.get(0).toString() : parts.get(0) - ); - } - - String outString = StringJoinInternalBit(parts, parts2, start, ""); - - for (int i = start + 1; i < length; i++) - { - outString += StringJoinInternalBit(parts, parts2, i, separator); - } - - return outString; - } - - static String StringJoinInternalBit(ArrayList parts, ArrayList parts2, int i, String separator) - { - String bit = ""; - - if (parts == null) - { - if (parts2.size() >= i - 1) - { - bit = parts2.get(i).toString(); - } - } - else if (parts.size() >= i - 1) - { - bit = parts.get(i); - } - - return separator + bit; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7d/d055a437b54b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7d/d055a437b54b00171c69d98bf667dda6 deleted file mode 100644 index 0b5389c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7d/d055a437b54b00171c69d98bf667dda6 +++ /dev/null @@ -1,1386 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Parts.size() == 2) - { - System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent); - } - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7f/201e55b66c4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7f/201e55b66c4c00171838d4a3813404a0 deleted file mode 100644 index 2de17cf..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/7f/201e55b66c4c00171838d4a3813404a0 +++ /dev/null @@ -1,261 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - X output = null; - try - { - output = GetFirst - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return output; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal, ExceptionTypes type) throws Exception - { - if (input == null) - { - return GetDefaultOrException(defaultVal, type); - } - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = input; - if (filter != null) - { - tempVar = WhereDict(input, filter); - } - if (tempVar == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(tempVar), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8/7059a1ef994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8/7059a1ef994a00171930ee4d171ed0de deleted file mode 100644 index e5d4edd..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8/7059a1ef994a00171930ee4d171ed0de +++ /dev/null @@ -1,1032 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8/80d1643f614c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8/80d1643f614c0017146ede6da4ae5d42 deleted file mode 100644 index b0d2ac5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8/80d1643f614c0017146ede6da4ae5d42 +++ /dev/null @@ -1,46 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import UnitParser.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class HCOther -{ - //While determining the system from the contituent parts, some units might be misinterpreted. - //For example: in ft/s, assuming SI (because of s) would be wrong. This collection avoids these - //problems by including the types to be ignored in these analyses, the neutral types. - public static ArrayList NeutralTypes; - - //List of types whose conversion requires more than just applying a conversion factor. - public static ArrayList SpecialConversionTypes; - - //Characters which are ignored while parsing units. For example: m or m. or (m) are identical. - //NOTE: the decimal separator characters would have to be removed from this list in order to - //start supporting decimal exponents. - public static ArrayList UnitParseIgnored; - - public static String Start() - { - NeutralTypes = new ArrayList() - {{ - add(UnitTypes.Time); add(UnitTypes.Angle); add(UnitTypes.SolidAngle); - add(UnitTypes.ElectricCurrent); add(UnitTypes.AmountOfSubstance); - add(UnitTypes.Temperature); - }}; - - SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - UnitParseIgnored = new ArrayList() - {{ - add("."); add(","); add(":"); add(";"); add("_"); add("^"); add("+"); - add("#"); add("("); add(")"); add("["); add("]"); add("{"); add("}"); - add("="); add("!"); add("?"); add("@"); add("&"); - }}; - - return ""; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/20281bfe404c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/20281bfe404c00171eb8e3cba3fc21fa deleted file mode 100644 index ea844e9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/20281bfe404c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,69 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //Emulating the conditions of the original C# version where decimal numbers cannot be parsed as integer. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input) throws ParseException - { - System.out.println(input); - //Locale.US because of being the best equivalence for CultureInfo.InvariantCulture in the original C# code. - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/20ea0a4cb14a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/20ea0a4cb14a00171059ebc16969059f deleted file mode 100644 index 5fc6b1a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/20ea0a4cb14a00171059ebc16969059f +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - System.out.println(tempInfo.Value); - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/d0f3ce84b94a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/d0f3ce84b94a0017160ae291ab4667e2 deleted file mode 100644 index c2ad921..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/d0f3ce84b94a0017160ae291ab4667e2 +++ /dev/null @@ -1,431 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.next(); - System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - System.out.println("here"); - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/d0ff117a644c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/d0ff117a644c0017146ede6da4ae5d42 deleted file mode 100644 index 6781f7e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/81/d0ff117a644c0017146ede6da4ae5d42 +++ /dev/null @@ -1,437 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - System.out.println("Condition 4 true"); - //This condition is true. - } - if (!new UnitP("wrong").Error.Type == UnitP.ErrorTypes.None) - { - System.out.println("Condition 5 true"); - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/82/4046f3909e4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/82/4046f3909e4a00171930ee4d171ed0de deleted file mode 100644 index bc30f0d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/82/4046f3909e4a00171930ee4d171ed0de +++ /dev/null @@ -1,51 +0,0 @@ -package test0; - -import java.util.Comparator; -import java.util.HashMap; - -import InternalUnitParser.CSharpAdaptation.Linq; -import InternalUnitParser.Hardcoding.HCPrefixes; -import UnitParser.UnitP; -import UnitParser.UnitSymbols; - -public class Main -{ - public static void main(String[] args) throws Exception - { - HashMap test0 = new HashMap(); - test0.put("Three", 3.0); - test0.put("One", 1.0); - test0.put("Four", 4.0); - test0.put("Two", 2.0); - test0.put("Five", 5.0); - - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - test0, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - - for(Double item: HCPrefixes.BigSIPrefixValues) - { - System.out.println(item); - } - - - //UnitP test = UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")); - //UnitP.Addition(UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ")); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/82/a07ef4b4a94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/82/a07ef4b4a94a00171059ebc16969059f deleted file mode 100644 index d0f364d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/82/a07ef4b4a94a00171059ebc16969059f +++ /dev/null @@ -1,1382 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - System.out.println(parseInfo.UnitInfo.System); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/83/b0896436f04c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/83/b0896436f04c00171048b3f61ecb42d3 deleted file mode 100644 index 55c9c8e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/83/b0896436f04c00171048b3f61ecb42d3 +++ /dev/null @@ -1,223 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -import java.util.AbstractMap; - -/**Contains the main information associated with unit prefixes.**/ -public class Prefix implements Comparable -{ - /**Name of the unit prefix.**/ - public final String Name; - /**Symbol of the unit prefix.**/ - public final String Symbol; - /**Multiplying factor associated with the unit prefix.**/ - public final double Factor; - /**Type of the unit prefix.**/ - public final PrefixTypes Type; - /**Usage conditions of the unit prefix.**/ - public final PrefixUsageTypes PrefixUsage; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /**Initialises a new Prefix instance.**/ - public Prefix() - { - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - PrefixUsage = PrefixUsageTypes.DefaultUsage; - } - - /** - Initialises a new Prefix instance. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - } - - /** - Initialises a new Prefix instance. - @param factor Multiplying factor to be used. - **/ - public Prefix(double factor) - { - this(factor, PrefixUsageTypes.DefaultUsage); - } - /** - Initialises a new Prefix instance. - @param factor Multiplying factor to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(factor, ""); - - if (Type != PrefixTypes.None) - { - Factor = factor; - Name = GetName(Type, Factor); - - Symbol = Linq.FirstOrDefaultDict - ( - Type == PrefixTypes.SI ? HCPrefixes.AllSIPrefixSymbols : - HCPrefixes.AllBinaryPrefixSymbols, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(null, 0.0) - ) - .getKey(); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param symbol Symbol (case does matter) defining the current prefix. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol) - { - this(symbol, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new Prefix instance. - @param symbol Symbol (case does matter) defining the current prefix. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(1.0, symbol); - - if (Type != PrefixTypes.None) - { - Symbol = symbol; - Factor = - ( - Type == PrefixTypes.SI ? - HCPrefixes.AllSIPrefixSymbols.get(symbol) : - HCPrefixes.AllBinaryPrefixSymbols.get(symbol) - ); - Name = GetName(Type, Factor); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param prefix Prefix variable whose information will be used. - **/ - public Prefix(Prefix prefix) - { - if (prefix == null) prefix = new Prefix(); - - Name = prefix.Name; - Symbol = prefix.Symbol; - Factor = prefix.Factor; - Type = prefix.Type; - PrefixUsage = prefix.PrefixUsage; - } - - static PrefixTypes GetType(double factor, String symbol) - { - PrefixTypes outType = PrefixTypes.None; - if (factor == 1.0 && symbol == "") return outType; - - if (factor != 1.0) - { - if (HCPrefixes.AllSIPrefixes.containsValue(factor)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixes.containsValue(factor)) - { - outType = PrefixTypes.Binary; - } - } - else - { - if (HCPrefixes.AllSIPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.Binary; - } - } - - return outType; - } - - static String GetName(PrefixTypes type, double factor) - { - return - ( - type == PrefixTypes.SI ? - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) : - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - ) - .getKey().toString(); - } - - @Override - /** - Compares the current instance against another Prefix one. - @param other The other Prefix instance. - **/ - public int compareTo(Prefix other) - { - return new Double(this.Factor).compareTo(other.Factor); - } - - @Override - /** - Determines whether the current Prefix instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((Prefix)obj); - } - - boolean Equals(Prefix other) - { - return - ( - other == null ? false : - Equals.PrefixesAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this Prefix instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/84/008a19cb514c00171860ae6a5189088d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/84/008a19cb514c00171860ae6a5189088d deleted file mode 100644 index 4808125..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/84/008a19cb514c00171860ae6a5189088d +++ /dev/null @@ -1,1382 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - System.out.println(stringToParse); - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/84/4031923a554c00171860ae6a5189088d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/84/4031923a554c00171860ae6a5189088d deleted file mode 100644 index f5fc595..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/84/4031923a554c00171860ae6a5189088d +++ /dev/null @@ -1,136 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = UnitInfo.Value; - //( - // improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - // MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - // UnitInfo.Value - //); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/84/906fff7eb64b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/84/906fff7eb64b00171c69d98bf667dda6 deleted file mode 100644 index 8bc50c8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/84/906fff7eb64b00171c69d98bf667dda6 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - System.out.println(parts2.get(0).Unit + " " + parts2.get(1).Unit); - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/2035718b2f4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/2035718b2f4a001712d4a4f7b050cac8 deleted file mode 100644 index 1d51737..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/2035718b2f4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1863 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - if(unitInfo.Parts.size() == 2) - { - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - } - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/507002a9f44c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/507002a9f44c00171048b3f61ecb42d3 deleted file mode 100644 index dbef27e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/507002a9f44c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1227 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - @return Current instance converted to targetUnit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return Current instance converted to targetUnit and targetPrefix. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - @return Current instance converted to targetUnitString. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/80f2c16e6d4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/80f2c16e6d4c00171838d4a3813404a0 deleted file mode 100644 index f5a270f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/80f2c16e6d4c00171838d4a3813404a0 +++ /dev/null @@ -1,262 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - if (input == null) return defaultVal; - - ArrayList tempVar = - ( - filter == null ? input : - Where(input, filter) - ); - if (tempVar == null) return defaultVal; - - return GetFirst(input2, filter, defaultVal); ; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(input); - try - { - output = (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return output; - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = - ( - filter == null ? input : - WhereDict(input, filter) - ); - if (tempVar == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(tempVar), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/a03b3f12f24c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/a03b3f12f24c00171048b3f61ecb42d3 deleted file mode 100644 index 2eb3f58..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/85/a03b3f12f24c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1214 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList variable including all the string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/86/4075b680f14c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/86/4075b680f14c00171048b3f61ecb42d3 deleted file mode 100644 index a8ffb88..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/86/4075b680f14c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1210 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information associated with converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/86/80186d65f04c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/86/80186d65f04c00171048b3f61ecb42d3 deleted file mode 100644 index e2f8a7f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/86/80186d65f04c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1209 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/87/900bdbd2964a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/87/900bdbd2964a00171930ee4d171ed0de deleted file mode 100644 index fe6df0e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/87/900bdbd2964a00171930ee4d171ed0de +++ /dev/null @@ -1,574 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - System.out.println(big2.Value); - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/87/a0012309b34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/87/a0012309b34a00171059ebc16969059f deleted file mode 100644 index 5355d2b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/87/a0012309b34a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - System.out.println(outInfo.Value); - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/87/b0237e1db14b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/87/b0237e1db14b00171c69d98bf667dda6 deleted file mode 100644 index 1589484..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/87/b0237e1db14b00171c69d98bf667dda6 +++ /dev/null @@ -1,240 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/88/00ccaf399e4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/88/00ccaf399e4a00171930ee4d171ed0de deleted file mode 100644 index bc30f0d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/88/00ccaf399e4a00171930ee4d171ed0de +++ /dev/null @@ -1,51 +0,0 @@ -package test0; - -import java.util.Comparator; -import java.util.HashMap; - -import InternalUnitParser.CSharpAdaptation.Linq; -import InternalUnitParser.Hardcoding.HCPrefixes; -import UnitParser.UnitP; -import UnitParser.UnitSymbols; - -public class Main -{ - public static void main(String[] args) throws Exception - { - HashMap test0 = new HashMap(); - test0.put("Three", 3.0); - test0.put("One", 1.0); - test0.put("Four", 4.0); - test0.put("Two", 2.0); - test0.put("Five", 5.0); - - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - test0, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - - for(Double item: HCPrefixes.BigSIPrefixValues) - { - System.out.println(item); - } - - - //UnitP test = UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")); - //UnitP.Addition(UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ")); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/88/b0e1bf967d4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/88/b0e1bf967d4c00171945f16efe0d9b5d deleted file mode 100644 index 2328c6f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/88/b0e1bf967d4c00171945f16efe0d9b5d +++ /dev/null @@ -1,435 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix.equals(new UnitP(1.0, "ks").UnitPrefix)) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton).equals(new UnitP("1 Mg*m/s2"))) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/89/10c1006d294a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/89/10c1006d294a001712d4a4f7b050cac8 deleted file mode 100644 index 969ac20..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/89/10c1006d294a001712d4a4f7b050cac8 +++ /dev/null @@ -1,13 +0,0 @@ -package test0; - -import UnitParser.UnitP; -import UnitParser.UnitSymbols; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP(1.0, UnitSymbols.Rod + "/h2"); - System.out.println(test.Error.Type); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/89/10eb39b8694c00171a25ec0b13e7f3ac b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/89/10eb39b8694c00171a25ec0b13e7f3ac deleted file mode 100644 index 5f84775..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/89/10eb39b8694c00171a25ec0b13e7f3ac +++ /dev/null @@ -1,1203 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /**Determines whether the current ErrorInfo instance is equal to other one.**/ - ///Other variable. - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /**Compares the current instance against another UnitP one.**/ - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /**Determines whether the current UnitP instance is equal to other one.**/ - ///Other variable. - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/0048a249f54c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/0048a249f54c00171048b3f61ecb42d3 deleted file mode 100644 index 66c19d0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/0048a249f54c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1235 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - @return Current instance converted to targetUnit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return Current instance converted to targetUnit and targetPrefix. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - @return Current instance converted to targetUnitString. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance unit. - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance unit. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance type. - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance type. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance type and system. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance type and system. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - @return ArrayList including all the units associated with the current instance type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - @return ArrayList including all the units associated with the current instance type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/0063a405f44c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/0063a405f44c00171048b3f61ecb42d3 deleted file mode 100644 index a3d3f5c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/0063a405f44c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1224 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/0074e89a414c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/0074e89a414c00171eb8e3cba3fc21fa deleted file mode 100644 index 6516789..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/0074e89a414c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,13 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP("J÷s-2"); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/509c30c0f14c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/509c30c0f14c00171048b3f61ecb42d3 deleted file mode 100644 index 66381c6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8b/509c30c0f14c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1212 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8c/4005bb98974a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8c/4005bb98974a00171930ee4d171ed0de deleted file mode 100644 index 756f43c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8c/4005bb98974a00171930ee4d171ed0de +++ /dev/null @@ -1,572 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8c/60416acc5b4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8c/60416acc5b4c0017146ede6da4ae5d42 deleted file mode 100644 index 9145f7e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8c/60416acc5b4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1200 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - ///Determines whether the current UnitP instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this UnitP instance. - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8d/50928273c14a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8d/50928273c14a00171634abff01ee97d5 deleted file mode 100644 index e26a0d7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8d/50928273c14a00171634abff01ee97d5 +++ /dev/null @@ -1,20 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits); - return; - UnitP test = UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8d/9034a573794c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8d/9034a573794c00171945f16efe0d9b5d deleted file mode 100644 index f828b57..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8d/9034a573794c00171945f16efe0d9b5d +++ /dev/null @@ -1,336 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -//This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). -//The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - -public class ExceptionInstantiation -{ - public static UnitInfo NewUnitInfo() - { - UnitInfo output = null; - - try - { - output = new UnitInfo(); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, int baseTenExponent) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value, baseTenExponent); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(Units unit) - { - return NewUnitInfo(unit, 1.0); - } - - public static UnitInfo NewUnitInfo(Units unit, double factor) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unit, factor); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, Units unit, Prefix prefix) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value, unit, prefix); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value) - { - return NewUnitInfo(value, null); - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value, exceptionHandling, prefixUsage); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, ArrayList parts) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value); - - if (parts != null) - { - output.Parts = new ArrayList(parts); - } - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(ArrayList parts) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(); - output.Parts = new ArrayList(parts); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, double value) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Value = value; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, ErrorTypes errorType) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Error = new ErrorInfo(errorType); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(ErrorTypes errorType) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(); - output.Error = new ErrorInfo(errorType); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, Units unit) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Unit = unit; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, Units unit, double factor) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Unit = unit; - output.Prefix = new Prefix(factor); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, double value, int baseTenExponent) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Value = value; - output.BaseTenExponent = baseTenExponent; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, Prefix prefix) - { - return NewUnitInfo(unitInfo, unitInfo.BaseTenExponent, prefix); - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, int baseTenExponent, Prefix prefix) - { - return NewUnitInfo(unitInfo, unitInfo.Value, baseTenExponent, prefix); - } - - public static UnitInfo NewUnitInfo(UnitP unitP, double value, int baseTenExponent, Prefix prefix) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitP); - output.BaseTenExponent = baseTenExponent; - output.Prefix = new Prefix(prefix); - output.Value = value; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, double value, int baseTenExponent, Prefix prefix) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.BaseTenExponent = baseTenExponent; - output.Prefix = new Prefix(prefix); - output.Value = value; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, Units unit, ArrayList parts) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Unit = unit; - output.Parts = new ArrayList(parts); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, Units unit, Prefix prefix, boolean getParts) - { - return NewUnitInfo - ( - value, unit, prefix, getParts, ExceptionHandlingTypes.AlwaysTriggerException - ); - } - - public static UnitInfo NewUnitInfo(double value, Units unit, Prefix prefix, boolean getParts, ExceptionHandlingTypes exceptionHandling) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value, unit, prefix, getParts, exceptionHandling); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitP unitP) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitP); - } - catch(Exception e) { } - - return output; - } - - public static ErrorInfo NewErrorInfo(ErrorTypes errorType) - { - ErrorInfo output = null; - - try - { - output = new ErrorInfo(errorType); - } - catch(Exception e) { } - - return output; - } - - public static ErrorInfo NewErrorInfo(ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling) - { - ErrorInfo output = null; - - try - { - output = new ErrorInfo(errorType, exceptionHandling); - } - catch(Exception e) { } - - return output; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8e/507870cf624c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8e/507870cf624c0017146ede6da4ae5d42 deleted file mode 100644 index cb30097..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8e/507870cf624c0017146ede6da4ae5d42 +++ /dev/null @@ -1,223 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -import java.util.AbstractMap; - -public class Prefix implements Comparable -{ - /**Name of the unit prefix.**/ - public final String Name; - /**Symbol of the unit prefix.**/ - public final String Symbol; - /**Multiplying factor associated with the unit prefix.**/ - public final double Factor; - /**Type of the unit prefix.**/ - public final PrefixTypes Type; - /**Usage conditions of the unit prefix.**/ - public final PrefixUsageTypes PrefixUsage; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /**Initialises a new Prefix instance.**/ - public Prefix() - { - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - PrefixUsage = PrefixUsageTypes.DefaultUsage; - } - - /** - Initialises a new Prefix instance. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - } - - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor) - { - this(factor, PrefixUsageTypes.DefaultUsage); - } - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(factor, ""); - - if (Type != PrefixTypes.None) - { - Factor = factor; - Name = GetName(Type, Factor); - - Symbol = Linq.FirstOrDefaultDict - ( - Type == PrefixTypes.SI ? HCPrefixes.AllSIPrefixSymbols : - HCPrefixes.AllBinaryPrefixSymbols, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(null, 0.0) - ) - .getKey(); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol) - { - this(symbol, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(1.0, symbol); - - if (Type != PrefixTypes.None) - { - Symbol = symbol; - Factor = - ( - Type == PrefixTypes.SI ? - HCPrefixes.AllSIPrefixSymbols.get(symbol) : - HCPrefixes.AllBinaryPrefixSymbols.get(symbol) - ); - Name = GetName(Type, Factor); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name prefix Prefix variable whose information will be used. - **/ - public Prefix(Prefix prefix) - { - if (prefix == null) prefix = new Prefix(); - - Name = prefix.Name; - Symbol = prefix.Symbol; - Factor = prefix.Factor; - Type = prefix.Type; - PrefixUsage = prefix.PrefixUsage; - } - - private static PrefixTypes GetType(double factor, String symbol) - { - PrefixTypes outType = PrefixTypes.None; - if (factor == 1.0 && symbol == "") return outType; - - if (factor != 1.0) - { - if (HCPrefixes.AllSIPrefixes.containsValue(factor)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixes.containsValue(factor)) - { - outType = PrefixTypes.Binary; - } - } - else - { - if (HCPrefixes.AllSIPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.Binary; - } - } - - return outType; - } - - private static String GetName(PrefixTypes type, double factor) - { - return - ( - type == PrefixTypes.SI ? - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) : - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - ) - .getKey().toString(); - } - - @Override - ///Compares the current instance against another Prefix one. - ///The other Prefix instance. - public int compareTo(Prefix other) - { - return new Double(this.Factor).compareTo - ( - new Double(other.Factor) - ); - } - - @Override - ///Determines whether the current Prefix instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((Prefix)obj); - } - - boolean Equals(Prefix other) - { - return - ( - other == null ? false : - Equals.PrefixesAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this Prefix instance. - public int hashCode() { return 0; } - -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8e/90c7dfaa9e4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8e/90c7dfaa9e4a00171930ee4d171ed0de deleted file mode 100644 index b3deed6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8e/90c7dfaa9e4a00171930ee4d171ed0de +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8f/5049b3ae944a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8f/5049b3ae944a00171930ee4d171ed0de deleted file mode 100644 index d04b403..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8f/5049b3ae944a00171930ee4d171ed0de +++ /dev/null @@ -1,571 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, - unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8f/a06d73599c4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8f/a06d73599c4a00171930ee4d171ed0de deleted file mode 100644 index 47dd077..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/8f/a06d73599c4a00171930ee4d171ed0de +++ /dev/null @@ -1,1858 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - System.out.println(targetExponent + " " + targetInfo.Value + " " + prefixFactor); - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - //System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9/b040b20bb34b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9/b040b20bb34b00171c69d98bf667dda6 deleted file mode 100644 index 43a6748..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9/b040b20bb34b00171c69d98bf667dda6 +++ /dev/null @@ -1,1382 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent); - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/91/5032ad585b4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/91/5032ad585b4c0017146ede6da4ae5d42 deleted file mode 100644 index 83c1a51..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/91/5032ad585b4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1199 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - ///Determines whether the current UnitP instance is equal to other one. - ///Other variable. - public boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - @Override - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/92/70546c20294c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/92/70546c20294c00171ae7fcf2c321c986 deleted file mode 100644 index bcb2fea..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/92/70546c20294c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - System.out.println(info2.Value + " " + info2.BaseTenExponent); - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/92/80cefd5e8f4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/92/80cefd5e8f4a00171930ee4d171ed0de deleted file mode 100644 index f148261..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/92/80cefd5e8f4a00171930ee4d171ed0de +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - System.out.println(tempInfos[0].Value + " " + tempInfos[0].BaseTenExponent + " " + tempInfos[0].Prefix.Factor + " -- " + tempInfos[1].Value + " " + tempInfos[1].BaseTenExponent + " " + tempInfos[1].Prefix.Factor); - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/92/90ca1d5e964a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/92/90ca1d5e964a00171930ee4d171ed0de deleted file mode 100644 index a6b9617..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/92/90ca1d5e964a00171930ee4d171ed0de +++ /dev/null @@ -1,574 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - System.out.println(big2.Value); - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - System.out.println(big2.Value); - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/93/30b98873f84c001712ece6513f6adb77 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/93/30b98873f84c001712ece6513f6adb77 deleted file mode 100644 index f6c1b38..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/93/30b98873f84c001712ece6513f6adb77 +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/4051b69cb44b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/4051b69cb44b00171c69d98bf667dda6 deleted file mode 100644 index a3290e5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/4051b69cb44b00171c69d98bf667dda6 +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/506e4fb7984a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/506e4fb7984a00171930ee4d171ed0de deleted file mode 100644 index 64c139b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/506e4fb7984a00171930ee4d171ed0de +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - System.out.println(outInfo.Value + " " + outInfo.BaseTenExponent + " " + outInfo.Prefix.Factor); - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/a0ea40d52b4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/a0ea40d52b4a001712d4a4f7b050cac8 deleted file mode 100644 index 1e20509..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/a0ea40d52b4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1033 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - System.out.println("asdfasf"); - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/b09c1134b64b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/b09c1134b64b00171c69d98bf667dda6 deleted file mode 100644 index ab19a36..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/94/b09c1134b64b00171c69d98bf667dda6 +++ /dev/null @@ -1,1389 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Parts.size() == 2) - { - //System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent); - System.out.println(parseInfo.UnitInfo.Parts.get(0).Unit + " " + parseInfo.UnitInfo.Parts.get(1).Unit); - } - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - System.out.println(tempInfo.Value + " " + tempInfo.BaseTenExponent); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/96/204f6631f04c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/96/204f6631f04c00171048b3f61ecb42d3 deleted file mode 100644 index 7e74d01..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/96/204f6631f04c00171048b3f61ecb42d3 +++ /dev/null @@ -1,224 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -import java.util.AbstractMap; - -/**Contains the main information associated with unit prefixes.**/ -public class Prefix implements Comparable -{ - /**Name of the unit prefix.**/ - public final String Name; - /**Symbol of the unit prefix.**/ - public final String Symbol; - /**Multiplying factor associated with the unit prefix.**/ - public final double Factor; - /**Type of the unit prefix.**/ - public final PrefixTypes Type; - /**Usage conditions of the unit prefix.**/ - public final PrefixUsageTypes PrefixUsage; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /**Initialises a new Prefix instance.**/ - public Prefix() - { - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - PrefixUsage = PrefixUsageTypes.DefaultUsage; - } - - /** - Initialises a new Prefix instance. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - } - - /** - Initialises a new Prefix instance. - @param factor Multiplying factor to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor) - { - this(factor, PrefixUsageTypes.DefaultUsage); - } - /** - Initialises a new Prefix instance. - @param factor Multiplying factor to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(factor, ""); - - if (Type != PrefixTypes.None) - { - Factor = factor; - Name = GetName(Type, Factor); - - Symbol = Linq.FirstOrDefaultDict - ( - Type == PrefixTypes.SI ? HCPrefixes.AllSIPrefixSymbols : - HCPrefixes.AllBinaryPrefixSymbols, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(null, 0.0) - ) - .getKey(); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param symbol Symbol (case does matter) defining the current prefix. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol) - { - this(symbol, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new Prefix instance. - @param symbol Symbol (case does matter) defining the current prefix. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(1.0, symbol); - - if (Type != PrefixTypes.None) - { - Symbol = symbol; - Factor = - ( - Type == PrefixTypes.SI ? - HCPrefixes.AllSIPrefixSymbols.get(symbol) : - HCPrefixes.AllBinaryPrefixSymbols.get(symbol) - ); - Name = GetName(Type, Factor); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param prefix Prefix variable whose information will be used. - **/ - public Prefix(Prefix prefix) - { - if (prefix == null) prefix = new Prefix(); - - Name = prefix.Name; - Symbol = prefix.Symbol; - Factor = prefix.Factor; - Type = prefix.Type; - PrefixUsage = prefix.PrefixUsage; - } - - static PrefixTypes GetType(double factor, String symbol) - { - PrefixTypes outType = PrefixTypes.None; - if (factor == 1.0 && symbol == "") return outType; - - if (factor != 1.0) - { - if (HCPrefixes.AllSIPrefixes.containsValue(factor)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixes.containsValue(factor)) - { - outType = PrefixTypes.Binary; - } - } - else - { - if (HCPrefixes.AllSIPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.Binary; - } - } - - return outType; - } - - static String GetName(PrefixTypes type, double factor) - { - return - ( - type == PrefixTypes.SI ? - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) : - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - ) - .getKey().toString(); - } - - @Override - /** - Compares the current instance against another Prefix one. - @param other The other Prefix instance. - **/ - public int compareTo(Prefix other) - { - return new Double(this.Factor).compareTo(other.Factor); - } - - @Override - /** - Determines whether the current Prefix instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((Prefix)obj); - } - - boolean Equals(Prefix other) - { - return - ( - other == null ? false : - Equals.PrefixesAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this Prefix instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/97/109c477f7a4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/97/109c477f7a4c00171945f16efe0d9b5d deleted file mode 100644 index 3379361..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/97/109c477f7a4c00171945f16efe0d9b5d +++ /dev/null @@ -1,351 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import UnitParser.*; - -import java.util.HashMap; -import java.util.Map; - -public class MethodsHardcoding -{ - /**Extracts all the AllUnits information and stores it in more-usable specific collections.**/ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static HashMap GetAllMain() - { - HashMap outDict = new HashMap(); - HCMain.AllUnitConversionFactors = new HashMap(); - HCMain.AllUnitSystems = new HashMap(); - HCMain.AllUnitStrings = new HashMap(); - - for (Map.Entry item : HCMain.AllUnits.entrySet()) - { - for (Map.Entry item2 : ((HashMap>)item.getValue()).entrySet()) - { - for (Map.Entry item3 : ((HashMap)item2.getValue()).entrySet()) - { - outDict.put((Units)item3.getKey(), (UnitTypes)item.getKey()); - HCMain.AllUnitSystems.put((Units)item3.getKey(), (UnitSystems)item2.getKey()); - HCMain.AllUnitConversionFactors.put((Units)item3.getKey(), (Double)item3.getValue()); - - if (!MethodsCommon.IsUnnamedUnit((Units)item3.getKey()) && StoreUnitNameIsOK((Units)item3.getKey())) - { - String unitName = ((Units)item3.getKey()).toString().toLowerCase(); - if (!HCMain.AllUnitStrings.containsKey(unitName)) - { - HCMain.AllUnitStrings.put(unitName, (Units)item3.getKey()); - } - } - } - } - } - - - PopulateAllUnitStrings(); - PopulateUnitSymbols2(); - PopulateBeyondDecimalConversionFactors(); - - HCMain.AllUnits = null; - - return outDict; - } - - static void PopulateBeyondDecimalConversionFactors() - { - HCMain.AllBeyondDecimalConversionFactors = new HashMap(); - - //Barn (b). Actual conversion factor 1E-28. - HCMain.AllBeyondDecimalConversionFactors.put - ( - UnitConversionFactors.Barn, ExceptionInstantiation.NewUnitInfo(1.0, -28) - ); - - //Debye (D). Actual conversion factor 3.33564095E-30. - HCMain.AllBeyondDecimalConversionFactors.put - ( - UnitConversionFactors.Debye, ExceptionInstantiation.NewUnitInfo(3.33564095, -30) - ); - } - - //All the unit names are stored in AllUnitStrings, whose elements are treated case insensitively. - //Not storing one of them would mean that all the associated String representations are always - //treated case-sensitively to avoid confusions. - static boolean StoreUnitNameIsOK(Units unit) - { - return - ( - unit == Units.Rad //rad/radian. - || unit == Units.Rutherford //rutherford/rod. - || unit == Units.Gal //gal/gallon. - ? false : true - ); - } - - //Stores additional symbols (case does matter) for some units. - static void PopulateUnitSymbols2() - { - - HCMain.AllUnitSymbols2 = new HashMap(); - - HCMain.AllUnitSymbols2.put("nmi", Units.NauticalMile); - HCMain.AllUnitSymbols2.put("ftm", Units.Fathom); - HCMain.AllUnitSymbols2.put("th", Units.Thou); - HCMain.AllUnitSymbols2.put("lnk", Units.Link); - HCMain.AllUnitSymbols2.put("fm", Units.Fermi); - HCMain.AllUnitSymbols2.put("psc", Units.Parsec); - HCMain.AllUnitSymbols2.put("l", Units.Litre); - HCMain.AllUnitSymbols2.put("p", Units.Pint); - HCMain.AllUnitSymbols2.put("impp", Units.ImperialPint); - HCMain.AllUnitSymbols2.put("uscp", Units.LiquidPint); - AddToAllUnitStrings("liquidp", Units.LiquidPint); - AddToAllUnitStrings("dryp", Units.DryPint); - HCMain.AllUnitSymbols2.put("cm3", Units.CubicCentimetre); - HCMain.AllUnitSymbols2.put("lbm", Units.Pound); - HCMain.AllUnitSymbols2.put("car", Units.Carat); - HCMain.AllUnitSymbols2.put("kgf", Units.Kilopond); - HCMain.AllUnitSymbols2.put("r", Units.Revolution); - HCMain.AllUnitSymbols2.put("stC", Units.Statcoulomb); - HCMain.AllUnitSymbols2.put("stA", Units.Statampere); - HCMain.AllUnitSymbols2.put("stV", Units.Statvolt); - HCMain.AllUnitSymbols2.put("stO", Units.Statohm); - HCMain.AllUnitSymbols2.put("stS", Units.Statsiemens); - HCMain.AllUnitSymbols2.put("st℧", Units.Statmho); - HCMain.AllUnitSymbols2.put("stF", Units.Statfarad); - HCMain.AllUnitSymbols2.put("stH", Units.Stathenry); - } - - //Populates all the unit String representations which aren't symbols (case doesn't matter). - static void PopulateAllUnitStrings() - { - Units unit = Units.Unitless; - AddToAllUnitStrings("ul", unit); - - unit = Units.Metre; - AddToAllUnitStrings("meter", unit); - AddToAllUnitStrings("mtr", unit); - - unit = Units.Centimetre; - AddToAllUnitStrings("centimeter", unit); - - unit = Units.AstronomicalUnit; - AddToAllUnitStrings("ua", unit); - - unit = Units.SurveyInch; - AddToAllUnitStrings("usin", unit); - - unit = Units.SurveyFoot; - AddToAllUnitStrings("usft", unit); - - unit = Units.SurveyYard; - AddToAllUnitStrings("usyd", unit); - - unit = Units.SurveyRod; - AddToAllUnitStrings("usrd", unit); - - unit = Units.SurveyChain; - AddToAllUnitStrings("usch", unit); - - unit = Units.SurveyLink; - AddToAllUnitStrings("usli", unit); - - unit = Units.SurveyMile; - AddToAllUnitStrings("usmi", unit); - - unit = Units.SurveyFathom; - AddToAllUnitStrings("usfathom", unit); - - unit = Units.MetricTon; - AddToAllUnitStrings("tonne", unit); - - unit = Units.Drachm; - AddToAllUnitStrings("dram", unit); - - unit = Units.LongQuarter; - AddToAllUnitStrings("longqr", unit); - AddToAllUnitStrings("ukqr", unit); - - unit = Units.ShortQuarter; - AddToAllUnitStrings("shortqr", unit); - AddToAllUnitStrings("usqr", unit); - - unit = Units.LongHundredweight; - AddToAllUnitStrings("longcwt", unit); - AddToAllUnitStrings("ukcwt", unit); - - unit = Units.ShortHundredweight; - AddToAllUnitStrings("shortcwt", unit); - AddToAllUnitStrings("uscwt", unit); - - //Plural support is automatically added to all the String representations (e.g., the ones added here), - //but not to the symbols. For example: the aforementioned mtr reference already includes mtrs. - unit = Units.Gram; - AddToAllUnitStrings("gs", unit); - - unit = Units.Pound; - AddToAllUnitStrings("lbs", unit); - - unit = Units.LongTon; - AddToAllUnitStrings("longtn", unit); - AddToAllUnitStrings("uktn", unit); - - unit = Units.ShortTon; - AddToAllUnitStrings("shorttn", unit); - AddToAllUnitStrings("ustn", unit); - - unit = Units.UnifiedAtomicMassUnit; - AddToAllUnitStrings("amu", unit); - - unit = Units.Second; - AddToAllUnitStrings("sec", unit); - - unit = Units.Hour; - AddToAllUnitStrings("hr", unit); - - unit = Units.SquareMetre; - AddToAllUnitStrings("squaremeter", unit); - AddSqCuToAllUnitStrings(new String[] { "m" }, unit); - - unit = Units.SquareCentimetre; - AddToAllUnitStrings("squarecentimeter", unit); - AddSqCuToAllUnitStrings(new String[] { "cm" }, unit); - - unit = Units.SquareFoot; - AddSqCuToAllUnitStrings(new String[] { "ft" }, unit); - - unit = Units.SquareInch; - AddSqCuToAllUnitStrings(new String[] { "in" }, unit); - - unit = Units.SquareRod; - AddSqCuToAllUnitStrings(new String[] { "rd" }, unit); - - unit = Units.SquarePerch; - AddSqCuToAllUnitStrings(new String[] { "perch" }, unit); - - unit = Units.SquarePole; - AddSqCuToAllUnitStrings(new String[] { "pole" }, unit); - - unit = Units.CubicMetre; - AddToAllUnitStrings("cubicmeter", unit); - AddSqCuToAllUnitStrings(new String[] { "m" }, unit, false); - - unit = Units.CubicCentimetre; - AddToAllUnitStrings("cubiccentimeter", unit); - AddSqCuToAllUnitStrings(new String[] { "cm" }, unit, false); - - unit = Units.CubicFoot; - AddSqCuToAllUnitStrings(new String[] { "ft" }, unit, false); - - unit = Units.CubicInch; - AddSqCuToAllUnitStrings(new String[] { "in" }, unit, false); - - unit = Units.Litre; - AddToAllUnitStrings("liter", unit); - AddToAllUnitStrings("ltr", unit); - - unit = Units.ImperialFluidOunce; - AddToAllUnitStrings("ukfloz", unit); - - unit = Units.USCSFluidOunce; - AddToAllUnitStrings("usfloz", unit); - - unit = Units.ImperialGill; - AddToAllUnitStrings("ukgi", unit); - - unit = Units.USCSGill; - AddToAllUnitStrings("usgi", unit); - - unit = Units.ImperialPint; - AddToAllUnitStrings("ukpt", unit); - AddToAllUnitStrings("ukp", unit); - - unit = Units.LiquidPint; - AddToAllUnitStrings("uspt", unit); - AddToAllUnitStrings("usp", unit); - - unit = Units.ImperialQuart; - AddToAllUnitStrings("ukqt", unit); - - unit = Units.LiquidQuart; - AddToAllUnitStrings("usqt", unit); - - unit = Units.ImperialGallon; - AddToAllUnitStrings("ukgal", unit); - - unit = Units.LiquidGallon; - AddToAllUnitStrings("usgal", unit); - - unit = Units.Degree; - AddToAllUnitStrings("deg", unit); - - unit = Units.Arcsecond; - AddToAllUnitStrings("arcsec", unit); - - unit = Units.Arcminute; - AddToAllUnitStrings("arcmin", unit); - - unit = Units.BritishThermalUnit; - AddToAllUnitStrings("btu", unit); - - unit = Units.ThermochemicalBritishThermalUnit; - AddToAllUnitStrings("thbtu", unit); - - unit = Units.Therm; - AddToAllUnitStrings("ecthm", unit); - - unit = Units.TonOfRefrigeration; - AddToAllUnitStrings("tr", unit); - AddToAllUnitStrings("rt", unit); - - unit = Units.DegreeCelsius; - AddToAllUnitStrings("degC", unit); - - unit = Units.DegreeFahrenheit; - AddToAllUnitStrings("degF", unit); - - unit = Units.DegreeRankine; - AddToAllUnitStrings("degR", unit); - - unit = Units.ReciprocalMetre; - AddToAllUnitStrings("inversemetre", unit); - AddToAllUnitStrings("inversemeter", unit); - AddToAllUnitStrings("reciprocalmeter", unit); - - unit = Units.InverseSquareMetre; - AddToAllUnitStrings("reciprocalsquaremetre", unit); - AddToAllUnitStrings("inversesquaremeter", unit); - AddToAllUnitStrings("reciprocalsquaremeter", unit); - - unit = Units.ImperialMilePerGallon; - AddToAllUnitStrings("ukmpg", unit); - - unit = Units.USCSMilePerGallon; - AddToAllUnitStrings("usmpg", unit); - - unit = Units.BitPerSecond; - AddToAllUnitStrings("bps", unit); - } - - static void AddSqCuToAllUnitStrings(String[] symbols, Units unit) - { - AddSqCuToAllUnitStrings(symbols, unit, true); - } - - static void AddSqCuToAllUnitStrings(String[] symbols, Units unit, boolean square) - { - String addition = (square ? "sq" : "cu"); - - for (String symbol: symbols) - { - AddToAllUnitStrings(addition + symbol, unit); - } - } - - static void AddToAllUnitStrings(String item, Units unit) - { - if (!HCMain.AllUnitStrings.containsKey(item)) - { - HCMain.AllUnitStrings.put(item, unit); - } - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/97/704a4aa8b04a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/97/704a4aa8b04a00171059ebc16969059f deleted file mode 100644 index fae1802..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/97/704a4aa8b04a00171059ebc16969059f +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - System.out.println("asfasf");//info2.Value + " " + info2.BaseTenExponent); - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/00331212934a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/00331212934a00171930ee4d171ed0de deleted file mode 100644 index 4734237..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/00331212934a00171930ee4d171ed0de +++ /dev/null @@ -1,567 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - System.out.println(operandArgs.get(0).Value + " " + operandArgs.get(0).BaseTenExponent + " " + operandArgs.get(0).Prefix.Factor + " -- " + operandArgs.get(1).Value + " " + operandArgs.get(1).BaseTenExponent + " " + operandArgs.get(1).Prefix.Factor); - - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/5004a634414c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/5004a634414c00171eb8e3cba3fc21fa deleted file mode 100644 index 23d12a5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/5004a634414c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,70 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - System.out.println(input + " " + output.IsOK); - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //Emulating the conditions of the original C# version where decimal numbers cannot be parsed as integer. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input) throws ParseException - { - //Locale.US because of being the best equivalence for CultureInfo.InvariantCulture in the original C# code. - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/508bf76cc34a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/508bf76cc34a00171634abff01ee97d5 deleted file mode 100644 index ed1e3b4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/508bf76cc34a00171634abff01ee97d5 +++ /dev/null @@ -1,107 +0,0 @@ -package InternalUnitParser.Operations; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class OperationsOther -{ - public static String GetOperationString(UnitP first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(UnitP first, Double second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), second.toString(), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(Double first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - first.toString(), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - private static String GetUnitPString(UnitP unitP) - { - return unitP.OriginalUnitString; - } - - private static String ConcatenateOperationString(String first, String second, char operation) - { - return (first + " " + operation + " " + second); - } - - //NOTE: the order within each char[] collection does matter. The first element will be treated as the default - //symbol for the given operation (e.g., used when creating a String including that operation). - public static HashMap> OperationSymbols; - - public static ArrayList UnitParseIgnored; - - //C# Decimal.MaxValue actual value. - //Although the range of the Java double type is notable bigger than this, MaxValue isn't modified to allow the Java and C# - //versions to output equivalent results. - public static final double MaxValue = 79228162514264337593543950335.0; - - //C# Decimal precision lowest limit. - // - public static final double MinValue = 0.0000000000000000000000000001; - - public static String Start() - { - OperationSymbols = new HashMap>() - { - { - { - put - ( - Operations.Addition, new ArrayList() - {{ - add('+'); - }} - ); - put - ( - Operations.Subtraction, new ArrayList() - {{ - add('-'); add('−'); add('—'); - }} - ); - put - ( - Operations.Multiplication, new ArrayList() - {{ - add('*'); add('x'); add('X'); add('×'); add('⊗'); add('â‹…'); add('·'); - }} - ); - put - ( - Operations.Division, new ArrayList() - {{ - add('/'); add('∕'); add('â„'); add('÷'); add('|'); add('\\'); - }} - ); - } - } - }; - - UnitParseIgnored = new ArrayList() - {{ - add("."); add(","); add(":"); add(";"); add("_"); add("^"); add("+"); - add("#"); add("("); add(")"); add("["); add("]"); add("{"); add("}"); - add("="); add("!"); add("?"); add("@"); add("&"); - }}; - - return ""; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/d0c79d15614c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/d0c79d15614c0017146ede6da4ae5d42 deleted file mode 100644 index 1a96396..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/98/d0c79d15614c0017146ede6da4ae5d42 +++ /dev/null @@ -1,281 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class HCPrefixes -{ - /** - Relates the SI prefixes (SIPrefixes enum) with their values (constants in the SIPrefixValues class). - **/ - public static HashMap AllSIPrefixes; - - //Relates the SI prefix strings (SIPrefixSymbols enum) with their values (constants in the SIPrefixValues class). - public static HashMap AllSIPrefixSymbols; - - //Relates the binary prefixes (BinaryPrefixes enum) with their values (constants in the BinaryPrefixValues class). - public static HashMap AllBinaryPrefixes; - - //Relates the binary prefix strings (BinaryPrefixSymbols enum) with their values (constants in the BinaryPrefixValues class). - public static HashMap AllBinaryPrefixSymbols; - - //Contains all the units outside the SI-prefix-supporting systems (i.e., UnitSystems.SI & UnitSystems.CGS) - //which do support SI prefixes by default. - public static ArrayList AllOtherSIPrefixUnits; - - //By default, global prefixes aren't used with compounds to avoid misunderstandings. For example: 1000 m^2 converted - //into k m^2 confused as km2. This collection includes all the compounds which might use prefixes. - public static ArrayList AllCompoundsUsingPrefixes; - - //Includes all the unit types which support binary prefixes by default. - public static ArrayList AllBinaryPrefixTypes; - - //All the collections below this line are secondary/used for very specific purposes. That's why they - //are only populated when being used for the first time. - - //The full names of all the SI/binary prefixes. - public static HashMap AllSIPrefixNames, AllBinaryPrefixNames; - - //Various collections used in prefix-related calculations. - public static ArrayList BigSIPrefixValues, SmallSIPrefixValues, BigBinaryPrefixValues, SmallBinaryPrefixValues; - - public static String Start() - { - AllBinaryPrefixTypes = new ArrayList() - {{ - add(UnitTypes.Information); add(UnitTypes.BitRate); add(UnitTypes.SymbolRate); - }}; - - AllCompoundsUsingPrefixes = new ArrayList() - {{ - //--- Area - add(Units.Rood); add(Units.Acre); add(Units.SurveyAcre); - - //--- Volume - add(Units.FluidOunce); add(Units.ImperialFluidOunce); add(Units.USCSFluidOunce); add(Units.Gill); - add(Units.ImperialGill); add(Units.USCSGill); add(Units.Pint); add(Units.ImperialPint); add(Units.LiquidPint); - add(Units.DryPint); add(Units.Quart); add(Units.ImperialQuart); add(Units.LiquidQuart); add(Units.DryQuart); - add(Units.Gallon); add(Units.LiquidGallon); add(Units.DryGallon); - - //--- Velocity - add(Units.Knot); - - //--- Acceleration - add(Units.Gal); - - //--- Force - add(Units.Newton); add(Units.Dyne); add(Units.PoundForce); add(Units.Poundal); add(Units.OunceForce); - - //--- Energy - add(Units.Joule); add(Units.Erg); add(Units.WattHour); add(Units.Calorie); add(Units.ThermochemicalCalorie); - add(Units.FoodCalorie); add(Units.BritishThermalUnit); add(Units.ThermochemicalBritishThermalUnit); - add(Units.Therm); add(Units.UKTherm); add(Units.USTherm); - - //--- Power - add(Units.Watt); add(Units.Horsepower); add(Units.MetricHorsepower); add(Units.ElectricHorsepower); - add(Units.BoilerHorsepower); add(Units.TonOfRefrigeration); - - //--- Pressure - add(Units.Pascal); add(Units.Barye); add(Units.Atmosphere); add(Units.TechnicalAtmosphere); add(Units.Bar); - add(Units.Torr); - - //--- Frequency - add(Units.Hertz); - - //--- Electric Charge - add(Units.AmpereHour); - - //--- Electric Current - add(Units.Ampere); add(Units.Statampere); add(Units.Abampere); add(Units.Biot); - - //--- Electric Voltage - add(Units.Volt); add(Units.Statvolt); add(Units.Abvolt); - - //--- Electric Resitance - add(Units.Ohm); add(Units.Statohm); add(Units.Abohm); - - //--- Electric Conductance - add(Units.Siemens); add(Units.Mho); add(Units.Gemmho); add(Units.Statsiemens); add(Units.Statmho); - add(Units.Absiemens); add(Units.Abmho); - - //--- Electric Capacitance - add(Units.Farad); add(Units.Statfarad); add(Units.Abfarad); - - //--- Electric Inductance - add(Units.Henry); add(Units.Stathenry); add(Units.Abhenry); - - //--- Electric Dipole Moment - add(Units.Debye); - - //--- Wavenumber - add(Units.Kayser); - - //--- Viscosity - add(Units.Poise); - - //--- Kinematic Viscosity - add(Units.Stokes); - - //--- Solid Angle - add(Units.Steradian); - - //--- Luminous Flux - add(Units.Lumen); - - //--- Luminous Energy - add(Units.Talbot); - - //--- Luminance - add(Units.Stilb); add(Units.Nit); add(Units.Lambert); add(Units.FootLambert); - - //--- Illuminance - add(Units.Lux); add(Units.Phot); add(Units.FootCandle); - - //--- Magnetic Flux - add(Units.Weber); add(Units.Maxwell); - - //--- Magnetic Field H - add(Units.Oersted); - - //--- Magnetic Field B - add(Units.Tesla); add(Units.Gauss); - - //--- Absorbed Dose - add(Units.Gray); add(Units.Rad); - - //--- Equivalent Dose - add(Units.Sievert); add(Units.REM); - - //--- Exposure - add(Units.Roentgen); - - //--- Catalytic Activity - add(Units.Katal); - - //--- Bit Rate - add(Units.BitPerSecond); - }}; - - AllOtherSIPrefixUnits = new ArrayList() - {{ - //--- Length - add(Units.Parsec); - - //--- Mass - add(Units.MetricTon); add(Units.Dalton); add(Units.UnifiedAtomicMassUnit); - - //--- Area - add(Units.Are); add(Units.Barn); - - //--- Volume - add(Units.Litre); - - //--- Information - add(Units.Bit); add(Units.Byte); add(Units.Nibble); add(Units.Quartet); add(Units.Octet); - - //--- Energy - add(Units.Electronvolt); add(Units.WattHour); add(Units.Calorie); add(Units.ThermochemicalCalorie); - - //--- Pressure - add(Units.Bar); add(Units.Torr); - - //--- Electric Charge - add(Units.AmpereHour); - - //--- Logarithmic - add(Units.Bel); add(Units.Neper); - - //--- Radioactivity - add(Units.Curie); - - //--- Bit Rate - add(Units.BitPerSecond); - - //--- Symbol Rate - add(Units.Baud); - }}; - - AllBinaryPrefixSymbols = new HashMap() - { - { - put(BinaryPrefixSymbols.Kibi, BinaryPrefixValues.Kibi); - put(BinaryPrefixSymbols.Mebi, BinaryPrefixValues.Mebi); - put(BinaryPrefixSymbols.Gibi, BinaryPrefixValues.Gibi); - put(BinaryPrefixSymbols.Tebi, BinaryPrefixValues.Tebi); - put(BinaryPrefixSymbols.Pebi, BinaryPrefixValues.Pebi); - put(BinaryPrefixSymbols.Exbi, BinaryPrefixValues.Exbi); - put(BinaryPrefixSymbols.Zebi, BinaryPrefixValues.Zebi); - put(BinaryPrefixSymbols.Yobi, BinaryPrefixValues.Yobi); - } - }; - - AllBinaryPrefixes = new HashMap() - { - { - put(BinaryPrefixes.Kibi, BinaryPrefixValues.Kibi); - put(BinaryPrefixes.Mebi, BinaryPrefixValues.Mebi); - put(BinaryPrefixes.Gibi, BinaryPrefixValues.Gibi); - put(BinaryPrefixes.Tebi, BinaryPrefixValues.Tebi); - put(BinaryPrefixes.Pebi, BinaryPrefixValues.Pebi); - put(BinaryPrefixes.Exbi, BinaryPrefixValues.Exbi); - put(BinaryPrefixes.Zebi, BinaryPrefixValues.Zebi); - put(BinaryPrefixes.Yobi, BinaryPrefixValues.Yobi); - } - }; - - AllSIPrefixSymbols = new HashMap() - { - { - put(SIPrefixSymbols.Yotta, SIPrefixValues.Yotta); - put(SIPrefixSymbols.Zetta, SIPrefixValues.Zetta); - put(SIPrefixSymbols.Exa, SIPrefixValues.Exa); - put(SIPrefixSymbols.Peta, SIPrefixValues.Peta); - put(SIPrefixSymbols.Tera, SIPrefixValues.Tera); - put(SIPrefixSymbols.Giga, SIPrefixValues.Giga); - put(SIPrefixSymbols.Mega, SIPrefixValues.Mega); - put(SIPrefixSymbols.Kilo, SIPrefixValues.Kilo); - put(SIPrefixSymbols.Hecto, SIPrefixValues.Hecto); - put(SIPrefixSymbols.Deca, SIPrefixValues.Deca); - put(SIPrefixSymbols.Deci, SIPrefixValues.Deci); - put(SIPrefixSymbols.Centi, SIPrefixValues.Centi); - put(SIPrefixSymbols.Milli, SIPrefixValues.Milli); - put(SIPrefixSymbols.Micro, SIPrefixValues.Micro); - put(SIPrefixSymbols.Nano, SIPrefixValues.Nano); - put(SIPrefixSymbols.Pico, SIPrefixValues.Pico); - put(SIPrefixSymbols.Femto, SIPrefixValues.Femto); - put(SIPrefixSymbols.Atto, SIPrefixValues.Atto); - put(SIPrefixSymbols.Zepto, SIPrefixValues.Zepto); - put(SIPrefixSymbols.Yocto, SIPrefixValues.Yocto); - } - }; - - AllSIPrefixes = new HashMap() - { - { - put(SIPrefixes.Yotta, SIPrefixValues.Yotta); - put(SIPrefixes.Zetta, SIPrefixValues.Zetta); - put(SIPrefixes.Exa, SIPrefixValues.Exa); - put(SIPrefixes.Peta, SIPrefixValues.Peta); - put(SIPrefixes.Tera, SIPrefixValues.Tera); - put(SIPrefixes.Giga, SIPrefixValues.Giga); - put(SIPrefixes.Mega, SIPrefixValues.Mega); - put(SIPrefixes.Kilo, SIPrefixValues.Kilo); - put(SIPrefixes.Hecto, SIPrefixValues.Hecto); - put(SIPrefixes.Deca, SIPrefixValues.Deca); - put(SIPrefixes.Deci, SIPrefixValues.Deci); - put(SIPrefixes.Centi, SIPrefixValues.Centi); - put(SIPrefixes.Milli, SIPrefixValues.Milli); - put(SIPrefixes.Micro, SIPrefixValues.Micro); - put(SIPrefixes.Nano, SIPrefixValues.Nano); - put(SIPrefixes.Pico, SIPrefixValues.Pico); - put(SIPrefixes.Femto, SIPrefixValues.Femto); - put(SIPrefixes.Atto, SIPrefixValues.Atto); - put(SIPrefixes.Zepto, SIPrefixValues.Zepto); - put(SIPrefixes.Yocto, SIPrefixValues.Yocto); - } - }; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/99/103a95bbb34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/99/103a95bbb34a00171059ebc16969059f deleted file mode 100644 index dc43fb9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/99/103a95bbb34a00171059ebc16969059f +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/99/50ece40e5e4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/99/50ece40e5e4c0017146ede6da4ae5d42 deleted file mode 100644 index f4000ae..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/99/50ece40e5e4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1200 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - ///Determines whether the current UnitP instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this UnitP instance. - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/99/d013fb492b4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/99/d013fb492b4a001712d4a4f7b050cac8 deleted file mode 100644 index 5005ace..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/99/d013fb492b4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1166 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - System.out.println(unitP2.UnitInfo.Unit); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9b/501765c1c54a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9b/501765c1c54a00171634abff01ee97d5 deleted file mode 100644 index 1589484..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9b/501765c1c54a00171634abff01ee97d5 +++ /dev/null @@ -1,240 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9b/70e956788f4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9b/70e956788f4a00171930ee4d171ed0de deleted file mode 100644 index 4c24ba9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9b/70e956788f4a00171930ee4d171ed0de +++ /dev/null @@ -1,564 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9c/60908e5f1c4900171bf99b86feeed734 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9c/60908e5f1c4900171bf99b86feeed734 deleted file mode 100644 index 7ffb4ae..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9c/60908e5f1c4900171bf99b86feeed734 +++ /dev/null @@ -1,318 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - X output = null; - try - { - output = GetFirst - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return output; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal, ExceptionTypes type) throws Exception - { - if (input == null) - { - return GetDefaultOrException(defaultVal, type); - } - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return GetDefaultOrException(defaultVal, type); - } - - private static X GetDefaultOrException(X defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - public static Map.Entry FirstDict(HashMap input) throws Exception - { - return FirstDict(input, null); - } - - public static Map.Entry FirstDict(HashMap input, Predicate> filter) throws Exception - { - if (filter != null) input = WhereDict(input, filter); - - return GetFirstDict - ( - input, filter, null, ExceptionTypes.FirstDict - ); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - HashMap input2 = new HashMap - ( - filter == null ? input : WhereDict(input, filter) - ); - - Map.Entry output = null; - - try - { - output = GetFirstDict - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return output; - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null) return null; - - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal, ExceptionTypes type - ) - throws Exception - { - if (input == null) - { - return GetDefaultOrExceptionDict(defaultVal, type); - } - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return GetDefaultOrExceptionDict(defaultVal, type); - } - - private static Map.Entry GetDefaultOrExceptionDict(Map.Entry defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - private static void ThrowException(ExceptionTypes type) throws Exception - { - String method = "First"; - if (type == ExceptionTypes.FirstDict) - { - method = " (1-D collections)"; - } - else if (type == ExceptionTypes.First) - { - method = " (dictionaries)"; - } - - throw new Exception("Exception provoked by an error in the custom version of the " + method + " LINQ method."); - } - - enum ExceptionTypes { None, First, FirstDict } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9c/f000fac8f74c00171d64cefe2267baa0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9c/f000fac8f74c00171d64cefe2267baa0 deleted file mode 100644 index 0810233..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9c/f000fac8f74c00171d64cefe2267baa0 +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9d/2048c6d6994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9d/2048c6d6994a00171930ee4d171ed0de deleted file mode 100644 index 348e370..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9d/2048c6d6994a00171930ee4d171ed0de +++ /dev/null @@ -1,137 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = - ( - improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - UnitInfo.Value - ); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9e/50579afb984a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9e/50579afb984a00171930ee4d171ed0de deleted file mode 100644 index 34ad7ac..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9e/50579afb984a00171930ee4d171ed0de +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9e/c06d79152e4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9e/c06d79152e4a001712d4a4f7b050cac8 deleted file mode 100644 index 228cd42..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9e/c06d79152e4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9e/e096e061b24b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9e/e096e061b24b00171c69d98bf667dda6 deleted file mode 100644 index 1af0a75..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9e/e096e061b24b00171c69d98bf667dda6 +++ /dev/null @@ -1,244 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - System.out.println(outInfo.Value + " " + outInfo.BaseTenExponent); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/20ddbc62624c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/20ddbc62624c0017146ede6da4ae5d42 deleted file mode 100644 index 299a898..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/20ddbc62624c0017146ede6da4ae5d42 +++ /dev/null @@ -1,166 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return - ( - first.Error.equals(second.Error) - ); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type == ErrorTypes.None || secondInfo.Error.Type == ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first.Type == second.Type && - first.Factor == second.Factor - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling == second.ExceptionHandling && - first.Type == second.Type - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first.equals(null) ? second.equals(null) : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/804a009fb24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/804a009fb24a00171059ebc16969059f deleted file mode 100644 index bd3ad93..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/804a009fb24a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - System.out.println(outInfo.Value); - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/a0b54970994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/a0b54970994a00171930ee4d171ed0de deleted file mode 100644 index 4372db1..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/a0b54970994a00171930ee4d171ed0de +++ /dev/null @@ -1,1166 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - System.out.println(unitP2.UnitInfo.Value + " " + unitP2.UnitInfo.BaseTenExponent + " " + unitP2.UnitInfo.Prefix.Factor); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/c0f2608bf34c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/c0f2608bf34c00171048b3f61ecb42d3 deleted file mode 100644 index 9428eab..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/9f/c0f2608bf34c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1223 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList variable including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList variable including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList variable including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList variable including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.Prefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a/00c7aa1ac24a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a/00c7aa1ac24a00171634abff01ee97d5 deleted file mode 100644 index 3577163..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a/00c7aa1ac24a00171634abff01ee97d5 +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - System.out.println(parseInfo.UnitInfo.BaseTenExponent); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a1/60caf3c87e4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a1/60caf3c87e4c00171945f16efe0d9b5d deleted file mode 100644 index b021ef3..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a1/60caf3c87e4c00171945f16efe0d9b5d +++ /dev/null @@ -1,102 +0,0 @@ -package InternalUnitParser.Operations; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class OperationsOther -{ - public static String GetOperationString(UnitP first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(UnitP first, Double second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), second.toString(), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(Double first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - first.toString(), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - private static String GetUnitPString(UnitP unitP) - { - return unitP.OriginalUnitString; - } - - private static String ConcatenateOperationString(String first, String second, char operation) - { - return (first + " " + operation + " " + second); - } - - //NOTE: the order within each char[] collection does matter. The first element will be treated as the default - //symbol for the given operation (e.g., used when creating a String including that operation). - public static HashMap> OperationSymbols; - - public static ArrayList UnitParseIgnored; - - public static final double MaxValue = 79228162514264337593543950335.0; //C# Decimal.MaxValue actual value. - public static final double MinValue = 0.0000000000000000000000000001; //C# Decimal precision lowest limit. - - public static String Start() - { - OperationSymbols = new HashMap>() - { - { - { - put - ( - Operations.Addition, new ArrayList() - {{ - add('+'); - }} - ); - put - ( - Operations.Subtraction, new ArrayList() - {{ - add('-'); add('−'); add('—'); - }} - ); - put - ( - Operations.Multiplication, new ArrayList() - {{ - add('*'); add('x'); add('X'); add('×'); add('⊗'); add('â‹…'); add('·'); - }} - ); - put - ( - Operations.Division, new ArrayList() - {{ - add('/'); add('â„'); - //add('/'); add('∕'); add('â„'); add('÷'); add('|'); add('\\'); - }} - ); - } - } - }; - - UnitParseIgnored = new ArrayList() - {{ - add("."); add(","); add(":"); add(";"); add("_"); add("^"); add("+"); - add("#"); add("("); add(")"); add("["); add("]"); add("{"); add("}"); - add("="); add("!"); add("?"); add("@"); add("&"); - }}; - - return ""; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a1/b07c9d5ea84a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a1/b07c9d5ea84a00171059ebc16969059f deleted file mode 100644 index ba2b2f7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a1/b07c9d5ea84a00171059ebc16969059f +++ /dev/null @@ -1,247 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - System.out.println - ( - outInfo.Value + " " + outInfo.BaseTenExponent + " " + outInfo.Prefix.Factor + " -- " + - secondInfo.Value + " " + secondInfo.BaseTenExponent + " " + secondInfo.Prefix.Factor - ); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/0016c5d5b04b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/0016c5d5b04b00171c69d98bf667dda6 deleted file mode 100644 index beadc90..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/0016c5d5b04b00171c69d98bf667dda6 +++ /dev/null @@ -1,20 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test0 = new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits); - System.out.println(test0.ValueAndUnitString); - UnitP test = UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/30ade4348f4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/30ade4348f4a00171930ee4d171ed0de deleted file mode 100644 index 853a584..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/30ade4348f4a00171930ee4d171ed0de +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - System.out.println(tempInfos[0].Value + " " + tempInfos[0].BaseTenExponent + " -- " + tempInfos[1].Value + " " + tempInfos[1].BaseTenExponent); - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/40178a27b34b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/40178a27b34b00171c69d98bf667dda6 deleted file mode 100644 index 798eb56..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/40178a27b34b00171c69d98bf667dda6 +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/d0d8ecdac44a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/d0d8ecdac44a00171634abff01ee97d5 deleted file mode 100644 index 523f82c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a2/d0d8ecdac44a00171634abff01ee97d5 +++ /dev/null @@ -1,18 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - //UnitP test = UnitP.Division - //( - // new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - // new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - //); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a4/003aabe4b54b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a4/003aabe4b54b00171c69d98bf667dda6 deleted file mode 100644 index 65cffc5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a4/003aabe4b54b00171c69d98bf667dda6 +++ /dev/null @@ -1,1389 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Parts.size() == 2) - { - //System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent); - System.out.println(parseInfo.UnitInfo.Parts.get(0).Unit + " " + parseInfo.UnitInfo.Parts.get(1).Unit); - } - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - System.out.println("here"); - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a4/3023c1815c4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a4/3023c1815c4c0017146ede6da4ae5d42 deleted file mode 100644 index 37ee9df..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a4/3023c1815c4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,164 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - System.out.println(UnitPNonUnitInfoAreEqual(first, second)); - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return (first.Error.equals(second.Error)); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean NoNullEquals(UnitP first, UnitP second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type != ErrorTypes.None || secondInfo.Error.Type != ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean NoNullEquals(Prefix first, Prefix second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean NoNullEquals(UnitPart first, UnitPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - System.out.println(UnitPNonUnitInfoAreEqual(first, second)); - return - ( - first.ExceptionHandling.equals(second.ExceptionHandling) && - first.Type.equals(second.Type) - ); - } - - public static boolean NoNullEquals(ErrorInfo first, ErrorInfo second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && first.Type == second.Type - ); - } - - public static boolean NoNullEquals(CompoundPart first, CompoundPart second) - { - return - ( - first == null ? second == null : first.equals(second) - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a4/80ef6edcc54a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a4/80ef6edcc54a00171634abff01ee97d5 deleted file mode 100644 index 043d029..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a4/80ef6edcc54a00171634abff01ee97d5 +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a5/501fb4efb34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a5/501fb4efb34a00171059ebc16969059f deleted file mode 100644 index 1e48f6a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a5/501fb4efb34a00171059ebc16969059f +++ /dev/null @@ -1,1062 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - System.out.println(originalInfo.Value); - UnitInfo test = Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - System.out.println(test.Value + " asdfasdf"); - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a5/70c3b4fea84a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a5/70c3b4fea84a00171059ebc16969059f deleted file mode 100644 index d3391dc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a5/70c3b4fea84a00171059ebc16969059f +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - System.out.println(outInfo.Parts.size()); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - System.out.println(outInfo.Parts.size()); - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a5/c0ebf371b04a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a5/c0ebf371b04a00171059ebc16969059f deleted file mode 100644 index fec39e0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a5/c0ebf371b04a00171059ebc16969059f +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - System.out.println(info2.Value + " " + info2.BaseTenExponent); - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a8/5028b25bc34a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a8/5028b25bc34a00171634abff01ee97d5 deleted file mode 100644 index 5bb958e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a8/5028b25bc34a00171634abff01ee97d5 +++ /dev/null @@ -1,29 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - double test = 0.0000000000000000000000000001; - - while (test == 0.0) - { - test *= 10; - } - - System.out.println(test); - - //new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits); - - //UnitP test = UnitP.Division - //( - // new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - // new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - //); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a9/502c006bbc4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a9/502c006bbc4a0017160ae291ab4667e2 deleted file mode 100644 index a3eaab7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a9/502c006bbc4a0017160ae291ab4667e2 +++ /dev/null @@ -1,453 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a9/70a19bd5b24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a9/70a19bd5b24a00171059ebc16969059f deleted file mode 100644 index 0b1d322..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/a9/70a19bd5b24a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - System.out.println(outInfo.Value); - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/aa/402d473c314a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/aa/402d473c314a001712d4a4f7b050cac8 deleted file mode 100644 index 62d8ed6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/aa/402d473c314a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1870 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - - Map.Entry res11 = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ); - - Map.Entry res12 = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ); - - - //Original C# code -> .ThenByDescending(x => x.Exponent) - int res2 = new Integer(second.Exponent).compareTo(first.Exponent); - if (res11 == null && res12 == null) - { - return res2; - } - - int res1 = res11.getValue().compareTo(res12.getValue()); - - return - ( - res1 != 0 ? res1 : res2 - ); - } - } - ); - - if(unitInfo.Parts.size() == 2) - { - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - } - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/aa/90f310556d4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/aa/90f310556d4c00171838d4a3813404a0 deleted file mode 100644 index 7bfac5a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/aa/90f310556d4c00171838d4a3813404a0 +++ /dev/null @@ -1,253 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - if (input == null) return defaultVal; - - ArrayList tempVar = - ( - filter == null ? input : - Where(input, filter) - ); - if (tempVar == null) return defaultVal; - - return GetFirst(input2, filter, defaultVal); ; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = - ( - filter == null ? input : - WhereDict(input, filter) - ); - if (tempVar == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(tempVar), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ac/20d4ede46c4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ac/20d4ede46c4c00171838d4a3813404a0 deleted file mode 100644 index 80e67c9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ac/20d4ede46c4c00171838d4a3813404a0 +++ /dev/null @@ -1,244 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - return GetFirst(input2, filter, defaultVal); ; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = - ( - filter == null ? input : - WhereDict(input, filter) - ); - if (tempVar == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(tempVar), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ae/40bc5c1b9e4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ae/40bc5c1b9e4a00171930ee4d171ed0de deleted file mode 100644 index 30cc96a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ae/40bc5c1b9e4a00171930ee4d171ed0de +++ /dev/null @@ -1,44 +0,0 @@ -package test0; - -import java.util.Comparator; - -import InternalUnitParser.CSharpAdaptation.Linq; -import InternalUnitParser.Hardcoding.HCPrefixes; -import UnitParser.UnitP; -import UnitParser.UnitSymbols; - -public class Main -{ - public static void main(String[] args) throws Exception - { - - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - - for(Double item: HCPrefixes.BigSIPrefixValues) - { - System.out.println(item); - } - - - //UnitP test = UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")); - //UnitP.Addition(UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ")); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ae/6023b9102a4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ae/6023b9102a4a001712d4a4f7b050cac8 deleted file mode 100644 index 732656c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ae/6023b9102a4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - System.out.println(parseInfo.UnitInfo.Unit); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ae/f00e6af4b34b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ae/f00e6af4b34b00171c69d98bf667dda6 deleted file mode 100644 index 538d9db..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ae/f00e6af4b34b00171c69d98bf667dda6 +++ /dev/null @@ -1,244 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - System.out.println(outInfo.Value + " " + outInfo.BaseTenExponent); - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/20b1c10d314a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/20b1c10d314a001712d4a4f7b050cac8 deleted file mode 100644 index 18ae2ca..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/20b1c10d314a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1866 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - System.out.println(result); - - return - ( - result - //result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - //new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - if(unitInfo.Parts.size() == 2) - { - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - } - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/20b6cff6284c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/20b6cff6284c00171ae7fcf2c321c986 deleted file mode 100644 index 4e9c8cf..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/20b6cff6284c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - System.out.println(info2.Value + " " + info2.BaseTenExponent); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/b0975c059b4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/b0975c059b4a00171930ee4d171ed0de deleted file mode 100644 index 6e04af0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/b0975c059b4a00171930ee4d171ed0de +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/d01a542c554c00171860ae6a5189088d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/d01a542c554c00171860ae6a5189088d deleted file mode 100644 index 8804712..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/af/d01a542c554c00171860ae6a5189088d +++ /dev/null @@ -1,136 +0,0 @@ -package InternalUnitParser.Classes; - -import InternalUnitParser.CSharpAdaptation.ExceptionInstantiation; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -//Class helping to deal with the relevant number of constructors including quite a few readonly variables. -public class UnitPConstructor -{ - public Double Value; - public String OriginalUnitString, UnitString, ValueAndUnitString; - public UnitTypes UnitType; - public UnitSystems UnitSystem; - public UnitInfo UnitInfo; - public ErrorTypes ErrorType; - public ExceptionHandlingTypes ExceptionHandling; - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo) - { - this(originalUnitString, unitInfo, UnitTypes.None, UnitSystems.None, unitInfo.Error.Type); - } - - public UnitPConstructor(String originalUnitString, UnitInfo unitInfo, UnitTypes unitType) - { - this(originalUnitString, unitInfo, unitType, UnitSystems.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, - UnitTypes unitType, UnitSystems unitSystem - ) - { - this(originalUnitString, unitInfo, unitType, unitSystem, ErrorTypes.None); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - this - ( - originalUnitString, unitInfo, unitType, unitSystem, - errorType, exceptionHandling, false - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, boolean noPrefixImprovement - ) - { - this - ( - originalUnitString, unitInfo, unitType, - unitSystem, errorType, exceptionHandling, - noPrefixImprovement, true - ); - } - - public UnitPConstructor - ( - String originalUnitString, UnitInfo unitInfo, UnitTypes unitType, - UnitSystems unitSystem, ErrorTypes errorType, - ExceptionHandlingTypes exceptionHandling, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - OriginalUnitString = - ( - originalUnitString == null ? "" : - originalUnitString.trim() - ); - ErrorType = errorType; - ExceptionHandling = exceptionHandling; - - if (ErrorType != ErrorTypes.None) - { - UnitInfo = ExceptionInstantiation.NewUnitInfo(); - } - else - { - UnitInfo = MethodsUnitP.ImproveUnitInfo(unitInfo, noPrefixImprovement); - - UnitType = - ( - UnitInfo.Type != UnitTypes.None ? UnitInfo.Type : - MethodsCommon.GetTypeFromUnitInfo(UnitInfo) - ); - UnitSystem = - ( - UnitInfo.System != UnitSystems.None && UnitInfo.System != UnitSystems.Imperial ? - UnitInfo.System : MethodsCommon.GetSystemFromUnit(UnitInfo.Unit, false, true) - ); - if (UnitSystem == UnitSystems.Imperial && UnitInfo.Unit == Units.ValidImperialUSCSUnit) - { - UnitInfo.Unit = Units.ValidImperialUnit; - } - UnitString = MethodsCommon.GetUnitString(UnitInfo); - - Value = - ( - improveFinalValue ? - //Values like 1.999999 are assumed to be a not-that-good version of 2.0 + some precision loss. - //This assumption doesn't hold every time (e.g., input value which wasn't part of any operation). - MethodsUnitP.ImproveFinalValue(UnitInfo.Value) : - UnitInfo.Value - ); - - ValueAndUnitString = Value.toString() + - ( - UnitInfo.BaseTenExponent != 0 ? - "*10^" + UnitInfo.BaseTenExponent.toString() : "" - ) - + " " + UnitString; - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b/2053a1fcb04a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b/2053a1fcb04a00171059ebc16969059f deleted file mode 100644 index 2307183..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b/2053a1fcb04a00171059ebc16969059f +++ /dev/null @@ -1,1056 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - System.out.println(targetInfo2.Value + " " + targetInfo2.BaseTenExponent); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b/b0d779a09d4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b/b0d779a09d4a00171930ee4d171ed0de deleted file mode 100644 index 371deda..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b/b0d779a09d4a00171930ee4d171ed0de +++ /dev/null @@ -1,14 +0,0 @@ -package test0; - -import UnitParser.UnitP; -import UnitParser.UnitSymbols; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")); - //UnitP.Addition(UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ")); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b0/d07dc0c4b64b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b0/d07dc0c4b64b00171c69d98bf667dda6 deleted file mode 100644 index 9384aa6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b0/d07dc0c4b64b00171c69d98bf667dda6 +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - System.out.println(tempInfo.Value + " " + tempInfo.BaseTenExponent); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b0/f07931795b4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b0/f07931795b4c0017146ede6da4ae5d42 deleted file mode 100644 index 3b28e66..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b0/f07931795b4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1199 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - ///Determines whether the current UnitP instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b1/705611aeb44a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b1/705611aeb44a00171059ebc16969059f deleted file mode 100644 index 30d9646..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b1/705611aeb44a00171059ebc16969059f +++ /dev/null @@ -1,1067 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - UnitInfo test0 = ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ); - System.out.println(test0.Value + " " + newExponent); - UnitInfo test = Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - System.out.println(test.Value + " asdfasdf"); - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b1/c0b8ca5c7a4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b1/c0b8ca5c7a4c00171945f16efe0d9b5d deleted file mode 100644 index 7a481fe..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b1/c0b8ca5c7a4c00171945f16efe0d9b5d +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b2/10a74058a94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b2/10a74058a94a00171059ebc16969059f deleted file mode 100644 index 84eae11..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b2/10a74058a94a00171059ebc16969059f +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b2/70511b5bc14a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b2/70511b5bc14a00171634abff01ee97d5 deleted file mode 100644 index c26dee5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b2/70511b5bc14a00171634abff01ee97d5 +++ /dev/null @@ -1,243 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b3/f0f4ff98f14c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b3/f0f4ff98f14c00171048b3f61ecb42d3 deleted file mode 100644 index df2bc7d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b3/f0f4ff98f14c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1211 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b4/60388549ab4a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b4/60388549ab4a00171059ebc16969059f deleted file mode 100644 index 738dc77..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b4/60388549ab4a00171059ebc16969059f +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b4/a03bdaef794c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b4/a03bdaef794c00171945f16efe0d9b5d deleted file mode 100644 index 04531b4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b4/a03bdaef794c00171945f16efe0d9b5d +++ /dev/null @@ -1,2624 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; - -import java.util.AbstractMap; -import java.util.HashMap; -import java.util.stream.Collectors; - - -@SuppressWarnings("serial") -public class HCMain -{ - //Main classification for all the units (type, system and conversion factor). - //This dictionary represents an easily-modifiable container of well-structured unit information. - //After using all this information to create more specific/efficient collections, GetAllMain() deletes it. - public static HashMap>> AllUnits; - - //HashMap mostly meant to deal with the Imperial/USCS peculiar relationship. - public static HashMap AllBasicSystems; - - //Some times, all what matters is knowing whether the system is metric (SI/CGS) or English (Imperial/USCS). - public static HashMap AllMetricEnglish; - - //This collection relates all the unnamed units with their associated systems. - //There are many units which don't fit any Units enum case, the unnamed units. - //Unnamed units avoid a huge (and not too logical) hardcoding effort. - //Note that UnitParser supports much more units than just the members of the Units enum. - //By bearing in mind that any combination of named units forming a supported type is also - //supported, the total number of supported units is way too big to even think about facing - //it in a hardcoding-all-of-them way. - - public static HashMap DefaultUnnamedUnits; - - //Relates all the units with their respective types. - //The call to GetALLMain() also populates all the collections below this line. - - public static HashMap AllUnitTypes; - - //Relates all the units with their respective systems. - public static HashMap AllUnitSystems; - - //Relates all the units with their respective conversion factors. - public static HashMap AllUnitConversionFactors; - - //Includes all the supported unit string representations (case doesn't matter). - public static HashMap AllUnitStrings; - - //Includes secondary symbols for some units (case does matter). - public static HashMap AllUnitSymbols2; - - //Some conversion factors are too small/big for the decimal type. - public static HashMap AllBeyondDecimalConversionFactors; - - public static void Start() - { - AllUnits = new HashMap>>() - { - { - put - ( - UnitTypes.None, - new HashMap>() - { - { - put - ( - UnitSystems.SI, new HashMap() - { - { put(Units.ValidSIUnit, 1.0); } - } - ); - put - ( - UnitSystems.Imperial, new HashMap() - { - { put(Units.ValidImperialUSCSUnit, 1.0); put(Units.ValidImperialUnit, 1.0); } - } - ); - put - ( - UnitSystems.USCS, new HashMap() - { - { put(Units.ValidUSCSUnit, 1.0); } - } - ); - put - ( - UnitSystems.CGS, new HashMap() - { - { put(Units.ValidCGSUnit, 1.0); } - } - ); - put - ( - UnitSystems.None, new HashMap() - { - { put(Units.ValidUnit, 1.0); put(Units.Unitless, 1.0); } - } - ); - } - } - ); - put - ( - UnitTypes.Length, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Metre, UnitConversionFactors.Metre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Centimetre, UnitConversionFactors.Centimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Foot, UnitConversionFactors.Foot); - put(Units.Thou, UnitConversionFactors.Thou); - put(Units.Mil, UnitConversionFactors.Mil); - put(Units.Inch, UnitConversionFactors.Inch); - put(Units.Yard, UnitConversionFactors.Yard); - put(Units.Fathom, UnitConversionFactors.Fathom); - put(Units.Rod, UnitConversionFactors.Rod); - put(Units.Perch, UnitConversionFactors.Perch); - put(Units.Pole, UnitConversionFactors.Pole); - put(Units.Chain, UnitConversionFactors.Chain); - put(Units.Furlong, UnitConversionFactors.Furlong); - put(Units.Mile, UnitConversionFactors.Mile); - put(Units.Link, UnitConversionFactors.Link); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.SurveyInch, UnitConversionFactors.SurveyInch); - put(Units.SurveyFoot, UnitConversionFactors.SurveyFoot); - put(Units.SurveyYard, UnitConversionFactors.SurveyYard); - put(Units.SurveyRod, UnitConversionFactors.SurveyRod); - put(Units.SurveyChain, UnitConversionFactors.SurveyChain); - put(Units.SurveyLink, UnitConversionFactors.SurveyLink); - put(Units.SurveyMile, UnitConversionFactors.SurveyMile); - put(Units.SurveyFathom, UnitConversionFactors.SurveyFathom); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.AstronomicalUnit, UnitConversionFactors.AstronomicalUnit); - put(Units.NauticalMile, UnitConversionFactors.NauticalMile); - put(Units.Angstrom, UnitConversionFactors.Angstrom); - put(Units.Fermi, UnitConversionFactors.Fermi); - put(Units.LightYear, UnitConversionFactors.LightYear); - put(Units.Parsec, UnitConversionFactors.Parsec); - put(Units.Micron, UnitConversionFactors.Micron); - } - } - ); - } - } - ); - put - ( - UnitTypes.Mass, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Gram, UnitConversionFactors.Gram); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Pound, UnitConversionFactors.Pound); - put(Units.Grain, UnitConversionFactors.Grain); - put(Units.Drachm, UnitConversionFactors.Drachm); - put(Units.Ounce, UnitConversionFactors.Ounce); - put(Units.Stone, UnitConversionFactors.Stone); - put(Units.Slug, UnitConversionFactors.Slug); - put(Units.Quarter, UnitConversionFactors.Quarter); - put(Units.LongQuarter, UnitConversionFactors.LongQuarter); - put(Units.Hundredweight, UnitConversionFactors.Hundredweight); - put(Units.LongHundredweight, UnitConversionFactors.LongHundredweight); - put(Units.Ton, UnitConversionFactors.Ton); - put(Units.LongTon, UnitConversionFactors.LongTon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.ShortQuarter, UnitConversionFactors.ShortQuarter); - put(Units.ShortHundredweight, UnitConversionFactors.ShortHundredweight); - put(Units.ShortTon, UnitConversionFactors.ShortTon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.MetricTon, UnitConversionFactors.MetricTon); - put(Units.Dalton, UnitConversionFactors.Dalton); - put(Units.UnifiedAtomicMassUnit, UnitConversionFactors.UnifiedAtomicMassUnit); - put(Units.Carat, UnitConversionFactors.Carat); - } - } - ); - } - } - ); - put - ( - UnitTypes.Time, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Second, UnitConversionFactors.Second); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Minute, UnitConversionFactors.Minute); - put(Units.Hour, UnitConversionFactors.Hour); - put(Units.Day, UnitConversionFactors.Day); - put(Units.Shake, UnitConversionFactors.Shake); - } - } - ); - } - } - ); - put - ( - UnitTypes.Area, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquareMetre, UnitConversionFactors.SquareMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.SquareCentimetre, UnitConversionFactors.SquareCentimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.SquareFoot, UnitConversionFactors.SquareFoot); - put(Units.SquareInch, UnitConversionFactors.SquareInch); - put(Units.SquareRod, UnitConversionFactors.SquareRod); - put(Units.SquarePerch, UnitConversionFactors.SquarePerch); - put(Units.SquarePole, UnitConversionFactors.SquarePole); - put(Units.Rood, UnitConversionFactors.Rood); - put(Units.Acre, UnitConversionFactors.Acre); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.SurveyAcre, UnitConversionFactors.SurveyAcre); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Are, UnitConversionFactors.Are); - put(Units.Barn, UnitConversionFactors.Barn); - } - } - ); - } - } - ); - put - ( - UnitTypes.Volume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetre, UnitConversionFactors.CubicMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.CubicCentimetre, UnitConversionFactors.CubicCentimetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.CubicFoot, UnitConversionFactors.CubicFoot); - put(Units.CubicInch, UnitConversionFactors.CubicInch); - put(Units.FluidOunce, UnitConversionFactors.FluidOunce); - put(Units.ImperialFluidOunce, UnitConversionFactors.ImperialFluidOunce); - put(Units.Gill, UnitConversionFactors.Gill); - put(Units.ImperialGill, UnitConversionFactors.ImperialGill); - put(Units.Pint, UnitConversionFactors.Pint); - put(Units.ImperialPint, UnitConversionFactors.ImperialPint); - put(Units.Quart, UnitConversionFactors.Quart); - put(Units.ImperialQuart, UnitConversionFactors.ImperialQuart); - put(Units.Gallon, UnitConversionFactors.Gallon); - put(Units.ImperialGallon, UnitConversionFactors.ImperialGallon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.USCSFluidOunce, UnitConversionFactors.USCSFluidOunce); - put(Units.USCSGill, UnitConversionFactors.USCSGill); - put(Units.LiquidPint, UnitConversionFactors.LiquidPint); - put(Units.DryPint, UnitConversionFactors.DryPint); - put(Units.LiquidQuart, UnitConversionFactors.LiquidQuart); - put(Units.DryQuart, UnitConversionFactors.DryQuart); - put(Units.LiquidGallon, UnitConversionFactors.LiquidGallon); - put(Units.DryGallon, UnitConversionFactors.DryGallon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Litre, UnitConversionFactors.Litre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Angle, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Radian, UnitConversionFactors.Radian); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Degree, UnitConversionFactors.Degree); - put(Units.Arcminute, UnitConversionFactors.Arcminute); - put(Units.Arcsecond, UnitConversionFactors.Arcsecond); - put(Units.Revolution, UnitConversionFactors.Revolution); - put(Units.Gradian, UnitConversionFactors.Gradian); - put(Units.Gon, UnitConversionFactors.Gon); - } - } - ); - } - } - ); - put - ( - UnitTypes.Information, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bit, UnitConversionFactors.Bit); - put(Units.Byte, UnitConversionFactors.Byte); - put(Units.Nibble, UnitConversionFactors.Nibble); - put(Units.Quartet, UnitConversionFactors.Quartet); - put(Units.Octet, UnitConversionFactors.Octet); - } - } - ); - } - } - ); - put - ( - UnitTypes.Force, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Newton, UnitConversionFactors.Newton); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.PoundForce, UnitConversionFactors.PoundForce); - put(Units.Poundal, UnitConversionFactors.Poundal); - put(Units.OunceForce, UnitConversionFactors.OunceForce); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Dyne, UnitConversionFactors.Dyne); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Kilopond, UnitConversionFactors.Kilopond); - put(Units.Kip, UnitConversionFactors.Kip); - } - } - ); - } - } - ); - put - ( - UnitTypes.Velocity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerSecond, UnitConversionFactors.MetrePerSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.CentimetrePerSecond, UnitConversionFactors.CentimetrePerSecond); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootPerSecond, UnitConversionFactors.FootPerSecond); - put(Units.InchPerSecond, UnitConversionFactors.InchPerSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Knot, UnitConversionFactors.Knot); - put(Units.KilometrePerHour, UnitConversionFactors.KilometrePerHour); - put(Units.MilePerHour, UnitConversionFactors.MilePerHour); - } - } - ); - } - } - ); - put - ( - UnitTypes.Acceleration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerSquareSecond, UnitConversionFactors.MetrePerSquareSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Gal, UnitConversionFactors.Gal); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootPerSquareSecond, UnitConversionFactors.FootPerSquareSecond); - put(Units.InchPerSquareSecond, UnitConversionFactors.InchPerSquareSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.Energy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Joule, UnitConversionFactors.Joule); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.BritishThermalUnit, UnitConversionFactors.BritishThermalUnit); - put(Units.ThermochemicalBritishThermalUnit, UnitConversionFactors.ThermochemicalBritishThermalUnit); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Erg, UnitConversionFactors.Erg); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Electronvolt, UnitConversionFactors.Electronvolt); - put(Units.WattHour, UnitConversionFactors.WattHour); - put(Units.Calorie, UnitConversionFactors.Calorie); - put(Units.ThermochemicalCalorie, UnitConversionFactors.ThermochemicalBritishThermalUnit); - put(Units.FoodCalorie, UnitConversionFactors.FoodCalorie); - put(Units.Therm, UnitConversionFactors.Therm); - put(Units.UKTherm, UnitConversionFactors.UKTherm); - put(Units.USTherm, UnitConversionFactors.USTherm); - } - } - ); - } - } - ); - put - ( - UnitTypes.Power, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Watt, UnitConversionFactors.Watt); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.ErgPerSecond, UnitConversionFactors.ErgPerSecond); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.Horsepower, UnitConversionFactors.Horsepower); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.MetricHorsepower, UnitConversionFactors.MetricHorsepower); - put(Units.ElectricHorsepower, UnitConversionFactors.ElectricHorsepower); - put(Units.BoilerHorsepower, UnitConversionFactors.BoilerHorsepower); - put(Units.TonOfRefrigeration, UnitConversionFactors.TonOfRefrigeration); - } - } - ); - } - } - ); - put - ( - UnitTypes.Pressure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Pascal, UnitConversionFactors.Pascal); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Barye, UnitConversionFactors.Barye); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.PoundforcePerSquareInch, UnitConversionFactors.PoundforcePerSquareInch); - put(Units.PoundforcePerSquareFoot, UnitConversionFactors.PoundforcePerSquareFoot); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bar, UnitConversionFactors.Bar); - put(Units.Atmosphere, UnitConversionFactors.Atmosphere); - put(Units.TechnicalAtmosphere, UnitConversionFactors.TechnicalAtmosphere); - put(Units.MillimetreOfMercury, UnitConversionFactors.MillimetreOfMercury); - put(Units.InchOfMercury32F, UnitConversionFactors.InchOfMercury32F); - put(Units.InchOfMercury60F, UnitConversionFactors.InchOfMercury60F); - put(Units.Torr, UnitConversionFactors.Torr); - put(Units.KipPerSquareInch, UnitConversionFactors.KipPerSquareInch); - } - } - ); - } - } - ); - put - ( - UnitTypes.Frequency, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Hertz, UnitConversionFactors.Hertz); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.CyclePerSecond, UnitConversionFactors.CyclePerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCharge, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Coulomb, UnitConversionFactors.Coulomb); - put(Units.AmpereHour, UnitConversionFactors.AmpereHour); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Franklin, UnitConversionFactors.Franklin); - put(Units.Statcoulomb, UnitConversionFactors.Statcoulomb); - put(Units.ESUOfCharge, UnitConversionFactors.ESUOfCharge); - put(Units.Abcoulomb, UnitConversionFactors.Abcoulomb); - put(Units.EMUOfCharge, UnitConversionFactors.EMUOfCharge); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCurrent, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Ampere, UnitConversionFactors.Ampere); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statampere, UnitConversionFactors.Statampere); - put(Units.ESUOfCurrent, UnitConversionFactors.ESUOfCurrent); - put(Units.Abampere, UnitConversionFactors.Abampere); - put(Units.Biot, UnitConversionFactors.Biot); - put(Units.EMUOfCurrent, UnitConversionFactors.EMUOfCurrent); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricVoltage, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Volt, UnitConversionFactors.Volt); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statvolt, UnitConversionFactors.Statvolt); - put(Units.ESUOfElectricPotential, UnitConversionFactors.ESUOfElectricPotential); - put(Units.Abvolt, UnitConversionFactors.Abvolt); - put(Units.EMUOfElectricPotential, UnitConversionFactors.EMUOfElectricPotential); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricResistance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Ohm, UnitConversionFactors.Ohm); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statohm, UnitConversionFactors.Statohm); - put(Units.ESUOfResistance, UnitConversionFactors.ESUOfResistance); - put(Units.Abohm, UnitConversionFactors.Abohm); - put(Units.EMUOfResistance, UnitConversionFactors.EMUOfResistance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricResistivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.OhmMetre, UnitConversionFactors.OhmMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricConductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Siemens, UnitConversionFactors.Siemens); - put(Units.Mho, UnitConversionFactors.Mho); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statmho, UnitConversionFactors.Statmho); - put(Units.Statsiemens, UnitConversionFactors.Statsiemens); - put(Units.Abmho, UnitConversionFactors.Abmho); - put(Units.Absiemens, UnitConversionFactors.Absiemens); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Gemmho, UnitConversionFactors.Gemmho); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricConductivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SiemensPerMetre, UnitConversionFactors.SiemensPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricCapacitance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Farad, UnitConversionFactors.Farad); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Statfarad, UnitConversionFactors.Statfarad); - put(Units.ESUOfCapacitance, UnitConversionFactors.ESUOfCapacitance); - put(Units.Abfarad, UnitConversionFactors.Abfarad); - put(Units.EMUOfCapacitance, UnitConversionFactors.EMUOfCapacitance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricInductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Henry, UnitConversionFactors.Henry); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stathenry, UnitConversionFactors.Stathenry); - put(Units.ESUOfInductance, UnitConversionFactors.ESUOfInductance); - put(Units.Abhenry, UnitConversionFactors.Abhenry); - put(Units.EMUOfInductance, UnitConversionFactors.EMUOfInductance); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricDipoleMoment, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombMetre, UnitConversionFactors.CoulombMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Debye, UnitConversionFactors.Debye); - } - } - ); - } - } - ); - put - ( - UnitTypes.Temperature, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - //Mere Placeholders. Temperature conversions are managed through a function. - put(Units.Kelvin, 1.0); - put(Units.DegreeCelsius, 1.0); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.DegreeFahrenheit, 1.0); - put(Units.DegreeRankine, 1.0); - } - } - ); - } - } - ); - put - ( - UnitTypes.Wavenumber, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.ReciprocalMetre, UnitConversionFactors.ReciprocalMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Kayser, UnitConversionFactors.Kayser); - } - } - ); - } - } - ); - put - ( - UnitTypes.Viscosity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.PascalSecond, UnitConversionFactors.PascalSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Poise, UnitConversionFactors.Poise); - } - } - ); - } - } - ); - put - ( - UnitTypes.KinematicViscosity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquareMetrePerSecond, UnitConversionFactors.SquareMetrePerSecond); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stokes, UnitConversionFactors.Stokes); - } - } - ); - } - } - ); - put - ( - UnitTypes.AmountOfSubstance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Mole, UnitConversionFactors.Mole); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.PoundMole, UnitConversionFactors.PoundMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.Momentum, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonSecond, UnitConversionFactors.NewtonSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularVelocity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.RadianPerSecond, UnitConversionFactors.RadianPerSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.RevolutionPerMinute, UnitConversionFactors.RevolutionPerMinute); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularAcceleration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.RadianPerSquareSecond, UnitConversionFactors.RadianPerSquareSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.AngularMomentum, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JouleSecond, UnitConversionFactors.JouleSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.MomentOfInertia, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramSquareMetre, UnitConversionFactors.KilogramSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SolidAngle, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Steradian, UnitConversionFactors.Steradian); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.SquareDegree, UnitConversionFactors.SquareDegree); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousIntensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Candela, UnitConversionFactors.Candela); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousFlux, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Lumen, UnitConversionFactors.Lumen); - } - } - ); - } - } - ); - put - ( - UnitTypes.LuminousEnergy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.LumenSecond, UnitConversionFactors.LumenSecond); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Talbot, UnitConversionFactors.Talbot); - } - } - ); - } - } - ); - put - ( - UnitTypes.Luminance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CandelaPerSquareMetre, UnitConversionFactors.CandelaPerSquareMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Stilb, UnitConversionFactors.Stilb); - put(Units.Lambert, UnitConversionFactors.Lambert); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootLambert, UnitConversionFactors.FootLambert); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Nit, UnitConversionFactors.Nit); - } - } - ); - } - } - ); - put - ( - UnitTypes.Illuminance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Lux, UnitConversionFactors.Lux); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.FootCandle, UnitConversionFactors.FootCandle); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Phot, UnitConversionFactors.Phot); - } - } - ); - } - } - ); - put - ( - UnitTypes.Logarithmic, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Bel, UnitConversionFactors.Bel); - put(Units.Neper, UnitConversionFactors.Neper); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFlux, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Weber, UnitConversionFactors.Weber); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Maxwell, UnitConversionFactors.Maxwell); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFieldB, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Tesla, UnitConversionFactors.Tesla); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Gauss, UnitConversionFactors.Gauss); - } - } - ); - } - } - ); - put - ( - UnitTypes.MagneticFieldH, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.AmperePerMetre, UnitConversionFactors.AmperePerMetre); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Oersted, UnitConversionFactors.Oersted); - } - } - ); - } - } - ); - put - ( - UnitTypes.Radioactivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Becquerel, UnitConversionFactors.Becquerel); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Curie, UnitConversionFactors.Curie); - put(Units.DisintegrationsPerMinute, UnitConversionFactors.DisintegrationsPerMinute); - put(Units.DisintegrationsPerSecond, UnitConversionFactors.DisintegrationsPerSecond); - put(Units.Rutherford, UnitConversionFactors.Rutherford); - } - } - ); - } - } - ); - put - ( - UnitTypes.AbsorbedDose, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Gray, UnitConversionFactors.Gray); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Rad, UnitConversionFactors.Rad); - } - } - ); - } - } - ); - put - ( - UnitTypes.AbsorbedDoseRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.GrayPerSecond, UnitConversionFactors.GrayPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.EquivalentDose, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Sievert, UnitConversionFactors.Sievert); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.REM, UnitConversionFactors.REM); - } - } - ); - } - } - ); - put - ( - UnitTypes.Exposure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerKilogram, UnitConversionFactors.CoulombPerKilogram); - } - } - ); - put - ( - UnitSystems.CGS, - new HashMap() - { - { - put(Units.Roentgen, UnitConversionFactors.Roentgen); - } - } - ); - } - } - ); - put - ( - UnitTypes.CatalyticActivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.Katal, UnitConversionFactors.Katal); - } - } - ); - } - } - ); - put - ( - UnitTypes.CatalyticActivityConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KatalPerCubicMetre, UnitConversionFactors.KatalPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Jerk, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetrePerCubicSecond, UnitConversionFactors.MetrePerCubicSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.MassFlowRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerSecond, UnitConversionFactors.KilogramPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.Density, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerCubicMetre, UnitConversionFactors.KilogramPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.AreaDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerSquareMetre, UnitConversionFactors.KilogramPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.EnergyDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerCubicMetre, UnitConversionFactors.JoulePerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SpecificVolume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerKilogram, UnitConversionFactors.CubicMetrePerKilogram); - } - } - ); - } - } - ); - put - ( - UnitTypes.VolumetricFlowRate, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerSecond, UnitConversionFactors.CubicMetrePerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SurfaceTension, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerSquareMetre, UnitConversionFactors.JoulePerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SpecificWeight, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonPerCubicMetre, UnitConversionFactors.NewtonPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalConductivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerMetrePerKelvin, UnitConversionFactors.WattPerMetrePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalConductance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerKelvin, UnitConversionFactors.WattPerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalResistivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MetreKelvinPerWatt, UnitConversionFactors.MetreKelvinPerWatt); - } - } - ); - } - } - ); - put - ( - UnitTypes.ThermalResistance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KelvinPerWatt, UnitConversionFactors.KelvinPerWatt); - } - } - ); - } - } - ); - put - ( - UnitTypes.HeatTransferCoefficient, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSquareMetrePerKelvin, UnitConversionFactors.WattPerSquareMetrePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.HeatFluxDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSquareMetre, UnitConversionFactors.WattPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.Entropy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerKelvin, UnitConversionFactors.JoulePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectricFieldStrength, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonPerCoulomb, UnitConversionFactors.NewtonPerCoulomb); - put(Units.VoltPerMetre, UnitConversionFactors.VoltPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.LinearElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerMetre, UnitConversionFactors.CoulombPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SurfaceElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerSquareMetre, UnitConversionFactors.CoulombPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.VolumeElectricChargeDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CoulombPerCubicMetre, UnitConversionFactors.CoulombPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.CurrentDensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.AmperePerSquareMetre, UnitConversionFactors.AmperePerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermittivity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.FaradPerMetre, UnitConversionFactors.FaradPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.ElectromagneticPermeability, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.HenryPerMetre, UnitConversionFactors.HenryPerMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarEnergy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerMole, UnitConversionFactors.JoulePerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarEntropy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.JoulePerMolePerKelvin, UnitConversionFactors.JoulePerMolePerKelvin); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarVolume, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.CubicMetrePerMole, UnitConversionFactors.CubicMetrePerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarMass, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.KilogramPerMole, UnitConversionFactors.KilogramPerMole); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolarConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MolePerCubicMetre, UnitConversionFactors.MolePerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.MolalConcentration, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.MolePerKilogram, UnitConversionFactors.MolePerKilogram); - } - } - ); - } - } - ); - put - ( - UnitTypes.RadiantIntensity, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSteradian, UnitConversionFactors.WattPerSteradian); - } - } - ); - } - } - ); - put - ( - UnitTypes.Radiance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.WattPerSteradianPerSquareMetre, UnitConversionFactors.WattPerSteradianPerSquareMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.FuelEconomy, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.InverseSquareMetre, UnitConversionFactors.InverseSquareMetre); - } - } - ); - put - ( - UnitSystems.Imperial, - new HashMap() - { - { - put(Units.MilePerGallon, UnitConversionFactors.MilePerGallon); - put(Units.ImperialMilePerGallon, UnitConversionFactors.ImperialMilePerGallon); - } - } - ); - put - ( - UnitSystems.USCS, - new HashMap() - { - { - put(Units.USCSMilePerGallon, UnitConversionFactors.USCSMilePerGallon); - } - } - ); - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.KilometrePerLitre, UnitConversionFactors.KilometrePerLitre); - } - } - ); - } - } - ); - put - ( - UnitTypes.SoundExposure, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.SquarePascalSecond, UnitConversionFactors.SquarePascalSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SoundImpedance, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.PascalSecondPerCubicMetre, UnitConversionFactors.PascalSecondPerCubicMetre); - } - } - ); - } - } - ); - put - ( - UnitTypes.RotationalStiffness, - new HashMap>() - { - { - put - ( - UnitSystems.SI, - new HashMap() - { - { - put(Units.NewtonMetrePerRadian, UnitConversionFactors.NewtonMetrePerRadian); - } - } - ); - } - } - ); - put - ( - UnitTypes.BitRate, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.BitPerSecond, UnitConversionFactors.BitPerSecond); - } - } - ); - } - } - ); - put - ( - UnitTypes.SymbolRate, - new HashMap>() - { - { - put - ( - UnitSystems.None, - new HashMap() - { - { - put(Units.Baud, UnitConversionFactors.Baud); - } - } - ); - } - } - ); - } - }; - - AllBasicSystems = new HashMap() - { - { put(UnitSystems.SI, UnitSystems.SI); } - { put(UnitSystems.CGS, UnitSystems.CGS); } - { put(UnitSystems.Imperial, UnitSystems.Imperial); } - { put(UnitSystems.USCS, UnitSystems.Imperial); } - { put(UnitSystems.ImperialAndUSCS, UnitSystems.Imperial); } - { put(UnitSystems.None, UnitSystems.None); } - }; - - AllMetricEnglish = new HashMap() - { - { put(UnitSystems.SI, UnitSystems.SI); } - { put(UnitSystems.CGS, UnitSystems.SI); } - { put(UnitSystems.Imperial, UnitSystems.Imperial); } - { put(UnitSystems.USCS, UnitSystems.Imperial); } - { put(UnitSystems.ImperialAndUSCS, UnitSystems.Imperial); } - { put(UnitSystems.None, UnitSystems.None); } - }; - - DefaultUnnamedUnits = (HashMap)AllUnits.get(UnitTypes.None).entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - x.getValue(), new AbstractMap.SimpleEntry(Units.None, 0.0) - ) - .getKey() - ) - ); - - AllUnitTypes = MethodsHardcoding.GetAllMain(); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b5/20f9aa29bb4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b5/20f9aa29bb4a0017160ae291ab4667e2 deleted file mode 100644 index aa9c91d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b5/20f9aa29bb4a0017160ae291ab4667e2 +++ /dev/null @@ -1,432 +0,0 @@ -package Parts; - -import java.io.Console; -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - Console c = System.console(); - String input = c.readLine("Enter your first name: "); - Scanner scanner = new Scanner("System.in"); - //String input = scanner.nextLine(); - System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b7/f06392c6404c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b7/f06392c6404c00171eb8e3cba3fc21fa deleted file mode 100644 index dc14b36..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b7/f06392c6404c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,82 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".") || input.toLowerCase().contains("e")) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input) throws Exception - { - if - ( - input == null || Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(input.toLowerCase()), - x -> !Character.isDigit(x) && x != '.' && x != ',' && x != 'e', '\u0000' - ) - != '\u0000' - ) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - //Note that TryParseOutput analyses the exponential cases (i.e., including e + integer exponent) further. - throw new Exception(); - } - - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b9/4035e03b7a4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b9/4035e03b7a4c00171945f16efe0d9b5d deleted file mode 100644 index 289a66a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b9/4035e03b7a4c00171945f16efe0d9b5d +++ /dev/null @@ -1,624 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -// -Class including the main hardcoded resources used for internal purposes. -In the original C# code, all this is stored in different files in the Keywords/Private folder. - -@SuppressWarnings("serial") -public class HCUnits -{ - //Relates the primary string representations (constants in the UnitSymbols class) with the corresponding - //unit (element of the Units enum). - public static HashMap AllUnitSymbols; - - //Includes all the units with compound (= dividable by default) types which cannot be divided. - public static ArrayList AllNonDividableUnits; - - //English-system units which are identical in both Imperial and USCS. - public static ArrayList AllImperialAndUSCSUnits; - - public static void Start() - { - AllUnitSymbols = new HashMap() - { - //--- Unitless - { put("unitless", Units.Unitless); } - - //--- Length - { put(UnitSymbols.Metre, Units.Metre); } - { put(UnitSymbols.Centimetre, Units.Centimetre); } - { put(UnitSymbols.AstronomicalUnit, Units.AstronomicalUnit); } - { put(UnitSymbols.Inch, Units.Inch); } - { put(UnitSymbols.Foot, Units.Foot); } - { put(UnitSymbols.Yard, Units.Yard); } - { put(UnitSymbols.Mile, Units.Mile); } - { put(UnitSymbols.NauticalMile, Units.NauticalMile); } - { put(UnitSymbols.Thou, Units.Thou); } - { put(UnitSymbols.Mil, Units.Mil); } - { put(UnitSymbols.Fathom, Units.Fathom); } - { put(UnitSymbols.Rod, Units.Rod); } - { put(UnitSymbols.Perch, Units.Perch); } - { put(UnitSymbols.Pole, Units.Pole); } - { put(UnitSymbols.Chain, Units.Chain); } - { put(UnitSymbols.Furlong, Units.Furlong); } - { put(UnitSymbols.SurveyInch, Units.SurveyInch); } - { put(UnitSymbols.SurveyFoot, Units.SurveyFoot); } - { put(UnitSymbols.SurveyYard, Units.SurveyYard); } - { put(UnitSymbols.SurveyRod, Units.SurveyRod); } - { put(UnitSymbols.SurveyChain, Units.SurveyChain); } - { put(UnitSymbols.SurveyLink, Units.SurveyLink); } - { put(UnitSymbols.SurveyMile, Units.SurveyMile); } - { put(UnitSymbols.SurveyFathom, Units.SurveyFathom); } - { put(UnitSymbols.Link, Units.Link); } - { put(UnitSymbols.Angstrom, Units.Angstrom); } - { put(UnitSymbols.Fermi, Units.Fermi); } - { put(UnitSymbols.LightYear, Units.LightYear); } - { put(UnitSymbols.Parsec, Units.Parsec); } - { put(UnitSymbols.Micron, Units.Micron); } - - //--- Mass - { put(UnitSymbols.Gram, Units.Gram); } - { put(UnitSymbols.MetricTon, Units.MetricTon); } - { put(UnitSymbols.Grain, Units.Grain); } - { put(UnitSymbols.Drachm, Units.Drachm); } - { put(UnitSymbols.Ounce, Units.Ounce); } - { put(UnitSymbols.Pound, Units.Pound); } - { put(UnitSymbols.Stone, Units.Stone); } - { put(UnitSymbols.Slug, Units.Slug); } - { put(UnitSymbols.Quarter, Units.Quarter); } - { put(UnitSymbols.LongQuarter, Units.LongQuarter); } - { put(UnitSymbols.ShortQuarter, Units.ShortQuarter); } - { put(UnitSymbols.Hundredweight, Units.Hundredweight); } - { put(UnitSymbols.LongHundredweight, Units.LongHundredweight); } - { put(UnitSymbols.ShortHundredweight, Units.ShortHundredweight); } - { put(UnitSymbols.Ton, Units.Ton); } - { put(UnitSymbols.LongTon, Units.LongTon); } - { put(UnitSymbols.ShortTon, Units.ShortTon); } - { put(UnitSymbols.Carat, Units.Carat); } - { put(UnitSymbols.Dalton, Units.Dalton); } - { put(UnitSymbols.UnifiedAtomicMassUnit, Units.UnifiedAtomicMassUnit); } - - //--- Time - { put(UnitSymbols.Second, Units.Second); } - { put(UnitSymbols.Minute, Units.Minute); } - { put(UnitSymbols.Hour, Units.Hour); } - { put(UnitSymbols.Day, Units.Day); } - { put(UnitSymbols.Shake, Units.Shake); } - - //--- Area - { put(UnitSymbols.SquareMetre, Units.SquareMetre); } - { put(UnitSymbols.SquareCentimetre, Units.SquareCentimetre); } - { put(UnitSymbols.Are, Units.Are); } - { put(UnitSymbols.SquareFoot, Units.SquareFoot); } - { put(UnitSymbols.SquareInch, Units.SquareInch); } - { put(UnitSymbols.SquareRod, Units.SquareRod); } - { put(UnitSymbols.SquarePerch, Units.SquarePerch); } - { put(UnitSymbols.SquarePole, Units.SquarePole); } - { put(UnitSymbols.Rood, Units.Rood); } - { put(UnitSymbols.Acre, Units.Acre); } - { put(UnitSymbols.SurveyAcre, Units.SurveyAcre); } - { put(UnitSymbols.Barn, Units.Barn); } - - //--- Volume - { put(UnitSymbols.CubicMetre, Units.CubicMetre); } - { put(UnitSymbols.CubicCentimetre, Units.CubicCentimetre); } - { put(UnitSymbols.Litre, Units.Litre); } - { put(UnitSymbols.CubicFoot, Units.CubicFoot); } - { put(UnitSymbols.CubicInch, Units.CubicInch); } - { put(UnitSymbols.FluidOunce, Units.FluidOunce); } - { put(UnitSymbols.ImperialFluidOunce, Units.ImperialFluidOunce); } - { put(UnitSymbols.USCSFluidOunce, Units.USCSFluidOunce); } - { put(UnitSymbols.Gill, Units.Gill); } - { put(UnitSymbols.ImperialGill, Units.ImperialGill); } - { put(UnitSymbols.USCSGill, Units.USCSGill); } - { put(UnitSymbols.Pint, Units.Pint); } - { put(UnitSymbols.ImperialPint, Units.ImperialPint); } - { put(UnitSymbols.LiquidPint, Units.LiquidPint); } - { put(UnitSymbols.DryPint, Units.DryPint); } - { put(UnitSymbols.Quart, Units.Quart); } - { put(UnitSymbols.ImperialQuart, Units.ImperialQuart); } - { put(UnitSymbols.LiquidQuart, Units.LiquidQuart); } - { put(UnitSymbols.DryQuart, Units.DryQuart); } - { put(UnitSymbols.Gallon, Units.Gallon); } - { put(UnitSymbols.ImperialGallon, Units.ImperialGallon); } - { put(UnitSymbols.LiquidGallon, Units.LiquidGallon); } - { put(UnitSymbols.DryGallon, Units.DryGallon); } - - //--- Angle - { put(UnitSymbols.Radian, Units.Radian); } - { put(UnitSymbols.Degree, Units.Degree); } - { put(UnitSymbols.Arcminute, Units.Arcminute); } - { put(UnitSymbols.Arcsecond, Units.Arcsecond); } - { put(UnitSymbols.Revolution, Units.Revolution); } - { put(UnitSymbols.Gradian, Units.Gradian); } - { put(UnitSymbols.Gon, Units.Gon); } - - //--- Information - { put(UnitSymbols.Bit, Units.Bit); } - { put(UnitSymbols.Byte, Units.Byte); } - { put(UnitSymbols.Nibble, Units.Nibble); } - { put(UnitSymbols.Quartet, Units.Quartet); } - { put(UnitSymbols.Octet, Units.Octet); } - - //--- Force - { put(UnitSymbols.Newton, Units.Newton); } - { put(UnitSymbols.Kilopond, Units.Kilopond); } - { put(UnitSymbols.PoundForce, Units.PoundForce); } - { put(UnitSymbols.Kip, Units.Kip); } - { put(UnitSymbols.Poundal, Units.Poundal); } - { put(UnitSymbols.OunceForce, Units.OunceForce); } - { put(UnitSymbols.Dyne, Units.Dyne); } - - //--- Velocity - { put(UnitSymbols.MetrePerSecond, Units.MetrePerSecond); } - { put(UnitSymbols.CentimetrePerSecond, Units.CentimetrePerSecond); } - { put(UnitSymbols.FootPerSecond, Units.FootPerSecond); } - { put(UnitSymbols.InchPerSecond, Units.InchPerSecond); } - { put(UnitSymbols.Knot, Units.Knot); } - { put(UnitSymbols.KilometrePerHour, Units.KilometrePerHour); } - { put(UnitSymbols.MilePerHour, Units.MilePerHour); } - - //--- Acceleration - { put(UnitSymbols.MetrePerSquareSecond, Units.MetrePerSquareSecond); } - { put(UnitSymbols.Gal, Units.Gal); } - { put(UnitSymbols.FootPerSquareSecond, Units.FootPerSquareSecond); } - { put(UnitSymbols.InchPerSquareSecond, Units.InchPerSquareSecond); } - - //--- Energy - { put(UnitSymbols.Joule, Units.Joule); } - { put(UnitSymbols.Electronvolt, Units.Electronvolt); } - { put(UnitSymbols.WattHour, Units.WattHour); } - { put(UnitSymbols.BritishThermalUnit, Units.BritishThermalUnit); } - { put(UnitSymbols.ThermochemicalBritishThermalUnit, Units.ThermochemicalBritishThermalUnit); } - { put(UnitSymbols.Calorie, Units.Calorie); } - { put(UnitSymbols.ThermochemicalCalorie, Units.ThermochemicalCalorie); } - { put(UnitSymbols.FoodCalorie, Units.FoodCalorie); } - { put(UnitSymbols.Erg, Units.Erg); } - { put(UnitSymbols.Therm, Units.Therm); } - { put(UnitSymbols.UKTherm, Units.UKTherm); } - { put(UnitSymbols.USTherm, Units.USTherm); } - - //--- Power - { put(UnitSymbols.Watt, Units.Watt); } - { put(UnitSymbols.ErgPerSecond, Units.ErgPerSecond); } - { put(UnitSymbols.Horsepower, Units.Horsepower); } - { put(UnitSymbols.MetricHorsepower, Units.MetricHorsepower); } - { put(UnitSymbols.BoilerHorsepower, Units.BoilerHorsepower); } - { put(UnitSymbols.ElectricHorsepower, Units.ElectricHorsepower); } - { put(UnitSymbols.TonOfRefrigeration, Units.TonOfRefrigeration); } - - //--- Pressure - { put(UnitSymbols.Pascal, Units.Pascal); } - { put(UnitSymbols.Atmosphere, Units.Atmosphere); } - { put(UnitSymbols.TechnicalAtmosphere, Units.TechnicalAtmosphere); } - { put(UnitSymbols.Bar, Units.Bar); } - { put(UnitSymbols.PoundforcePerSquareInch, Units.PoundforcePerSquareInch); } - { put(UnitSymbols.PoundforcePerSquareFoot, Units.PoundforcePerSquareFoot); } - { put(UnitSymbols.MillimetreOfMercury, Units.MillimetreOfMercury); } - { put(UnitSymbols.InchOfMercury32F, Units.InchOfMercury32F); } - { put(UnitSymbols.InchOfMercury60F, Units.InchOfMercury60F); } - { put(UnitSymbols.Barye, Units.Barye); } - { put(UnitSymbols.Torr, Units.Torr); } - { put(UnitSymbols.KipPerSquareInch, Units.KipPerSquareInch); } - - //--- Frequency - { put(UnitSymbols.Hertz, Units.Hertz); } - { put(UnitSymbols.CyclePerSecond, Units.CyclePerSecond); } - - //--- Electric Charge - { put(UnitSymbols.Coulomb, Units.Coulomb); } - { put(UnitSymbols.AmpereHour, Units.AmpereHour); } - { put(UnitSymbols.Franklin, Units.Franklin); } - { put(UnitSymbols.Statcoulomb, Units.Statcoulomb); } - { put(UnitSymbols.ESUOfCharge, Units.ESUOfCharge); } - { put(UnitSymbols.Abcoulomb, Units.Abcoulomb); } - { put(UnitSymbols.EMUOfCharge, Units.EMUOfCharge); } - - //--- Electric Current - { put(UnitSymbols.Ampere, Units.Ampere); } - { put(UnitSymbols.Statampere, Units.Statampere); } - { put(UnitSymbols.ESUOfCurrent, Units.ESUOfCurrent); } - { put(UnitSymbols.Abampere, Units.Abampere); } - { put(UnitSymbols.EMUOfCurrent, Units.EMUOfCurrent); } - { put(UnitSymbols.Biot, Units.Biot); } - - //--- Electric Voltage - { put(UnitSymbols.Volt, Units.Volt); } - { put(UnitSymbols.Statvolt, Units.Statvolt); } - { put(UnitSymbols.ESUOfElectricPotential, Units.ESUOfElectricPotential); } - { put(UnitSymbols.Abvolt, Units.Abvolt); } - { put(UnitSymbols.EMUOfElectricPotential, Units.EMUOfElectricPotential); } - - //--- Electric Resistance - { put(UnitSymbols.Ohm, Units.Ohm); } - { put(UnitSymbols.Statohm, Units.Statohm); } - { put(UnitSymbols.ESUOfResistance, Units.ESUOfResistance); } - { put(UnitSymbols.Abohm, Units.Abohm); } - { put(UnitSymbols.EMUOfResistance, Units.EMUOfResistance); } - - //--- Electric Resistivity - { put(UnitSymbols.OhmMetre, Units.OhmMetre); } - - //--- Electric Conductance - { put(UnitSymbols.Siemens, Units.Siemens); } - { put(UnitSymbols.Mho, Units.Mho); } - { put(UnitSymbols.Gemmho, Units.Gemmho); } - { put(UnitSymbols.Statsiemens, Units.Statsiemens); } - { put(UnitSymbols.Statmho, Units.Statmho); } - { put(UnitSymbols.Absiemens, Units.Absiemens); } - { put(UnitSymbols.Abmho, Units.Abmho); } - - //--- Electric Conductivity - { put(UnitSymbols.SiemensPerMetre, Units.SiemensPerMetre); } - - //--- Electric Capacitance - { put(UnitSymbols.Farad, Units.Farad); } - { put(UnitSymbols.Statfarad, Units.Statfarad); } - { put(UnitSymbols.ESUOfCapacitance, Units.ESUOfCapacitance); } - { put(UnitSymbols.Abfarad, Units.Abfarad); } - { put(UnitSymbols.EMUOfCapacitance, Units.EMUOfCapacitance); } - - //--- Electric Inductance - { put(UnitSymbols.Henry, Units.Henry); } - { put(UnitSymbols.Stathenry, Units.Stathenry); } - { put(UnitSymbols.ESUOfInductance, Units.ESUOfInductance); } - { put(UnitSymbols.Abhenry, Units.Abhenry); } - { put(UnitSymbols.EMUOfInductance, Units.EMUOfInductance); } - - //--- Electric Dipole Moment - { put(UnitSymbols.CoulombMetre, Units.CoulombMetre); } - { put(UnitSymbols.Debye, Units.Debye); } - - //--- Temperature - { put(UnitSymbols.Kelvin, Units.Kelvin); } - { put(UnitSymbols.DegreeCelsius, Units.DegreeCelsius); } - { put(UnitSymbols.DegreeFahrenheit, Units.DegreeFahrenheit); } - { put(UnitSymbols.DegreeRankine, Units.DegreeRankine); } - - //--- Wavenumber - { put(UnitSymbols.ReciprocalMetre, Units.ReciprocalMetre); } - { put(UnitSymbols.Kayser, Units.Kayser); } - - //--- Viscosity - { put(UnitSymbols.PascalSecond, Units.PascalSecond); } - { put(UnitSymbols.Poise, Units.Poise); } - - //--- Kinematic Viscosity - { put(UnitSymbols.SquareMetrePerSecond, Units.SquareMetrePerSecond); } - { put(UnitSymbols.Stokes, Units.Stokes); } - - //--- Amount of Substance - { put(UnitSymbols.Mole, Units.Mole); } - { put(UnitSymbols.PoundMole, Units.PoundMole); } - - //--- Momentum - { put(UnitSymbols.NewtonSecond, Units.NewtonSecond); } - - //--- Angular Velocity - { put(UnitSymbols.RadianPerSecond, Units.RadianPerSecond); } - { put(UnitSymbols.RevolutionPerMinute, Units.RevolutionPerMinute); } - - //--- Angular Acceleration - { put(UnitSymbols.RadianPerSquareSecond, Units.RadianPerSquareSecond); } - - //--- Angular Momentum - { put(UnitSymbols.JouleSecond, Units.JouleSecond); } - - //--- Moment of Inertia - { put(UnitSymbols.KilogramSquareMetre, Units.KilogramSquareMetre); } - - //--- Solid Angle - { put(UnitSymbols.Steradian, Units.Steradian); } - { put(UnitSymbols.SquareDegree, Units.SquareDegree); } - - //--- Luminous Intensity - { put(UnitSymbols.Candela, Units.Candela); } - - //--- Luminous Flux - { put(UnitSymbols.Lumen, Units.Lumen); } - - //--- Luminous Energy - { put(UnitSymbols.LumenSecond, Units.LumenSecond); } - { put(UnitSymbols.Talbot, Units.Talbot); } - - //--- Luminance - { put(UnitSymbols.CandelaPerSquareMetre, Units.CandelaPerSquareMetre); } - { put(UnitSymbols.Nit, Units.Nit); } - { put(UnitSymbols.Stilb, Units.Stilb); } - { put(UnitSymbols.Lambert, Units.Lambert); } - { put(UnitSymbols.FootLambert, Units.FootLambert); } - - //--- Illuminance - { put(UnitSymbols.Lux, Units.Lux); } - { put(UnitSymbols.Phot, Units.Phot); } - { put(UnitSymbols.FootCandle, Units.FootCandle); } - - //--- Logarithmic - { put(UnitSymbols.Bel, Units.Bel); } - { put(UnitSymbols.Neper, Units.Neper); } - - //--- Magnetic Flux - { put(UnitSymbols.Weber, Units.Weber); } - { put(UnitSymbols.Maxwell, Units.Maxwell); } - - //--- Magnetic Field B - { put(UnitSymbols.Tesla, Units.Tesla); } - { put(UnitSymbols.Gauss, Units.Gauss); } - - //--- Magnetic Field H - { put(UnitSymbols.AmperePerMetre, Units.AmperePerMetre); } - { put(UnitSymbols.Oersted, Units.Oersted); } - - //--- Radioactivity - { put(UnitSymbols.Becquerel, Units.Becquerel); } - { put(UnitSymbols.Curie, Units.Curie); } - { put(UnitSymbols.DisintegrationsPerSecond, Units.DisintegrationsPerSecond); } - { put(UnitSymbols.DisintegrationsPerMinute, Units.DisintegrationsPerMinute); } - { put(UnitSymbols.Rutherford, Units.Rutherford); } - - //--- Absorbed Dose - { put(UnitSymbols.Gray, Units.Gray); } - { put(UnitSymbols.Rad, Units.Rad); } - - //--- Absorbed Dose Rate - { put(UnitSymbols.GrayPerSecond, Units.GrayPerSecond); } - - //--- Equivalent Dose - { put(UnitSymbols.Sievert, Units.Sievert); } - { put(UnitSymbols.REM, Units.REM); } - - //--- Exposure - { put(UnitSymbols.CoulombPerKilogram, Units.CoulombPerKilogram); } - { put(UnitSymbols.Roentgen, Units.Roentgen); } - - //--- Catalytic Activity - { put(UnitSymbols.Katal, Units.Katal); } - - //--- Catalytic Activity Concentration - { put(UnitSymbols.KatalPerCubicMetre, Units.KatalPerCubicMetre); } - - //--- Jerk - { put(UnitSymbols.MetrePerCubicSecond, Units.MetrePerCubicSecond); } - - //--- Mass Flow Rate - { put(UnitSymbols.KilogramPerSecond, Units.KilogramPerSecond); } - - //--- Density - { put(UnitSymbols.KilogramPerCubicMetre, Units.KilogramPerCubicMetre); } - - //--- Area Density - { put(UnitSymbols.KilogramPerSquareMetre, Units.KilogramPerSquareMetre); } - - //--- Energy Density - { put(UnitSymbols.JoulePerCubicMetre, Units.JoulePerCubicMetre); } - - //--- Specific Volume - { put(UnitSymbols.CubicMetrePerKilogram, Units.CubicMetrePerKilogram); } - - //--- Volumetric Flow Rate - { put(UnitSymbols.CubicMetrePerSecond, Units.CubicMetrePerSecond); } - - //--- Surface Tension - { put(UnitSymbols.JoulePerSquareMetre, Units.JoulePerSquareMetre); } - - //--- Specific Weight - { put(UnitSymbols.NewtonPerCubicMetre, Units.NewtonPerCubicMetre); } - - //--- Thermal Conductivity - { put(UnitSymbols.WattPerMetrePerKelvin, Units.WattPerMetrePerKelvin); } - - //--- Thermal Conductance - { put(UnitSymbols.WattPerKelvin, Units.WattPerKelvin); } - - //--- Thermal Resistivity - { put(UnitSymbols.MetreKelvinPerWatt, Units.MetreKelvinPerWatt); } - - //--- Thermal Resistance - { put(UnitSymbols.KelvinPerWatt, Units.KelvinPerWatt); } - - //--- Heat Transfer Coefficient - { put(UnitSymbols.WattPerSquareMetrePerKelvin, Units.WattPerSquareMetrePerKelvin); } - - //--- Heat Flux Density - { put(UnitSymbols.WattPerSquareMetre, Units.WattPerSquareMetre); } - - //--- Entropy - { put(UnitSymbols.JoulePerKelvin, Units.JoulePerKelvin); } - - //--- Electric Field Strength - { put(UnitSymbols.NewtonPerCoulomb, Units.NewtonPerCoulomb); } - { put(UnitSymbols.VoltPerMetre, Units.VoltPerMetre); } - - //--- Linear Electric Charge Density - { put(UnitSymbols.CoulombPerMetre, Units.CoulombPerMetre); } - - //--- Surface Electric Charge Density - { put(UnitSymbols.CoulombPerSquareMetre, Units.CoulombPerSquareMetre); } - - //--- Volume Electric Charge Density - { put(UnitSymbols.CoulombPerCubicMetre, Units.CoulombPerCubicMetre); } - - //--- Current Density - { put(UnitSymbols.AmperePerSquareMetre, Units.AmperePerSquareMetre); } - - //--- Electromagnetic Permittivity - { put(UnitSymbols.FaradPerMetre, Units.FaradPerMetre); } - - //--- Electromagnetic Permeability - { put(UnitSymbols.HenryPerMetre, Units.HenryPerMetre); } - - //--- Molar Energy - { put(UnitSymbols.JoulePerMole, Units.JoulePerMole); } - - //--- Molar Entropy - { put(UnitSymbols.JoulePerMolePerKelvin, Units.JoulePerMolePerKelvin); } - - //--- Molar Volume - { put(UnitSymbols.CubicMetrePerMole, Units.CubicMetrePerMole); } - - //--- Molar Mass - { put(UnitSymbols.KilogramPerMole, Units.KilogramPerMole); } - - //--- Molar Concentration - { put(UnitSymbols.MolePerCubicMetre, Units.MolePerCubicMetre); } - - //--- Molal Concentration - { put(UnitSymbols.MolePerKilogram, Units.MolePerKilogram); } - - //--- Radiant Intensity - { put(UnitSymbols.WattPerSteradian, Units.WattPerSteradian); } - - //--- Radiance - { put(UnitSymbols.WattPerSteradianPerSquareMetre, Units.WattPerSteradianPerSquareMetre); } - - //--- Fuel Economy - { put(UnitSymbols.InverseSquareMetre, Units.InverseSquareMetre); } - { put(UnitSymbols.MilePerGallon, Units.MilePerGallon); } - { put(UnitSymbols.ImperialMilePerGallon, Units.ImperialMilePerGallon); } - { put(UnitSymbols.USCSMilePerGallon, Units.USCSMilePerGallon); } - { put(UnitSymbols.KilometrePerLitre, Units.KilometrePerLitre); } - - //--- Sound Exposure - { put(UnitSymbols.SquarePascalSecond, Units.SquarePascalSecond); } - - //--- Sound Impedance - { put(UnitSymbols.PascalSecondPerCubicMetre, Units.PascalSecondPerCubicMetre); } - - //--- Rotational Stiffness - { put(UnitSymbols.NewtonMetrePerRadian, Units.NewtonMetrePerRadian); } - - //--- Bit Rate - { put(UnitSymbols.BitPerSecond, Units.BitPerSecond); } - - //--- Symbol Rate - { put(UnitSymbols.Baud, Units.Baud); } - }; - - AllNonDividableUnits = new ArrayList() - {{ - //--- Area - add(Units.Are); add(Units.Rood); add(Units.Acre); add(Units.Barn); add(Units.SurveyAcre); - - //--- Volume - add(Units.Litre); add(Units.FluidOunce); add(Units.ImperialFluidOunce); add(Units.USCSFluidOunce); add(Units.Gill); - add(Units.ImperialGill); add(Units.USCSGill); add(Units.Pint); add(Units.ImperialPint); add(Units.LiquidPint); - add(Units.DryPint); add(Units.Quart); add(Units.ImperialQuart); add(Units.LiquidQuart); add(Units.DryQuart); - add(Units.Gallon); add(Units.ImperialGallon); add(Units.LiquidGallon); add(Units.DryGallon); - - //--- Force - add(Units.Kilopond); add(Units.PoundForce); add(Units.Kip); add(Units.OunceForce); - - //--- Energy - add(Units.Electronvolt); add(Units.BritishThermalUnit); add(Units.ThermochemicalBritishThermalUnit); - add(Units.Calorie); add(Units.ThermochemicalCalorie); add(Units.FoodCalorie); add(Units.Therm); add(Units.UKTherm); - add(Units.USTherm); - - //--- Power - add(Units.Horsepower); add(Units.MetricHorsepower); add(Units.BoilerHorsepower); add(Units.ElectricHorsepower); - add(Units.TonOfRefrigeration); - - //--- Pressure - add(Units.Atmosphere); add(Units.TechnicalAtmosphere); add(Units.Bar); add(Units.MillimetreOfMercury); add(Units.InchOfMercury32F); - add(Units.InchOfMercury60F); add(Units.Torr); - - //--- Amount of substance - add(Units.PoundMole); - - //Note that all the electricity/magnetism CGS compounds are considered non-dividable. - //This is because of its multi-system peculiarities and what it entails. - //These are old units where the dividable-compound icing isn't expected to be that important. - //Compounds which might be defined without a direct reliance on electricity/magnetism units are - //dividable. For example, G (= Mx/cm2). - - //--- Electric Charge - add(Units.Franklin); add(Units.Statcoulomb); add(Units.ESUOfCharge); add(Units.Abcoulomb); add(Units.EMUOfCharge); - - //--- Electric Voltage - add(Units.ESUOfElectricPotential); add(Units.Statvolt); add(Units.EMUOfElectricPotential); add(Units.Abvolt); - - //--- Electric Resistance - add(Units.Statohm); add(Units.ESUOfResistance); add(Units.Abohm); add(Units.EMUOfResistance); - - //--- Electric Conductance - add(Units.Gemmho); add(Units.Statsiemens); add(Units.Statmho); add(Units.Absiemens); add(Units.Abmho); - - //--- Electric Capacitance - add(Units.Statfarad); add(Units.ESUOfCapacitance); add(Units.Abfarad); add(Units.EMUOfCapacitance); - - //--- Electric Inductance - add(Units.Stathenry); add(Units.ESUOfInductance); add(Units.Abhenry); add(Units.EMUOfInductance); - - //--- Electric Dipole Moment - add(Units.Debye); - - //--- Luminance - add(Units.Lambert); add(Units.FootLambert); - - //--- Magnetic Flux - add(Units.Maxwell); - - //--- Magnetic Field H - add(Units.Oersted); - - //--- Absorbed Dose - add(Units.Rad); - - //--- Equivalent Dose - add(Units.REM); - - //--- Exposure - add(Units.Roentgen); - }}; - - AllImperialAndUSCSUnits = new ArrayList() - {{ - //--- Length - add(Units.Inch); add(Units.Foot); add(Units.Yard); add(Units.Mile); add(Units.Thou); - add(Units.Mil); add(Units.Fathom); add(Units.Rod); add(Units.Perch); add(Units.Pole); - add(Units.Chain); add(Units.Furlong); add(Units.Link); - - //--- Mass - add(Units.Grain); add(Units.Drachm); add(Units.Ounce); add(Units.Pound); add(Units.Stone); - add(Units.Slug); - - //--- Area - add(Units.SquareInch); add(Units.SquareFoot); add(Units.SquareRod); add(Units.SquarePerch); - add(Units.SquarePole); add(Units.Rood); add(Units.Acre); - - //--- Volume - add(Units.CubicInch); add(Units.CubicFoot); - - //--- Force - add(Units.PoundForce); add(Units.Poundal); add(Units.OunceForce); - - //--- Velocity - add(Units.FootPerSecond); add(Units.InchPerSecond); add(Units.MilePerHour); - - //--- Acceleration - add(Units.FootPerSquareSecond); add(Units.InchPerSquareSecond); - - //--- Energy - add(Units.BritishThermalUnit); add(Units.ThermochemicalBritishThermalUnit); - - //--- Power - add(Units.Horsepower); - - //--- Pressure - add(Units.PoundforcePerSquareInch); add(Units.PoundforcePerSquareFoot); - - //--- Temperature - add(Units.DegreeFahrenheit); add(Units.DegreeRankine); - - //--- Luminance - add(Units.FootLambert); - - //--- Illuminance - add(Units.FootCandle); - }}; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b9/f0b2cd85294c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b9/f0b2cd85294c00171ae7fcf2c321c986 deleted file mode 100644 index 43846a2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/b9/f0b2cd85294c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - System.out.println(exponent); - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ba/6000be0e7f4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ba/6000be0e7f4c00171945f16efe0d9b5d deleted file mode 100644 index 212cab7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ba/6000be0e7f4c00171945f16efe0d9b5d +++ /dev/null @@ -1,102 +0,0 @@ -package InternalUnitParser.Operations; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class OperationsOther -{ - public static String GetOperationString(UnitP first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(UnitP first, Double second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), second.toString(), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(Double first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - first.toString(), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - private static String GetUnitPString(UnitP unitP) - { - return unitP.OriginalUnitString; - } - - private static String ConcatenateOperationString(String first, String second, char operation) - { - return (first + " " + operation + " " + second); - } - - //NOTE: the order within each char[] collection does matter. The first element will be treated as the default - //symbol for the given operation (e.g., used when creating a String including that operation). - public static HashMap> OperationSymbols; - - public static ArrayList UnitParseIgnored; - - public static final double MaxValue = 79228162514264337593543950335.0; //C# Decimal.MaxValue actual value. - public static final double MinValue = 0.0000000000000000000000000001; //C# Decimal precision lowest limit. - - public static String Start() - { - OperationSymbols = new HashMap>() - { - { - { - put - ( - Operations.Addition, new ArrayList() - {{ - add('+'); - }} - ); - put - ( - Operations.Subtraction, new ArrayList() - {{ - add('-'); add('−'); add('—'); - }} - ); - put - ( - Operations.Multiplication, new ArrayList() - {{ - add('*'); add('x'); add('X'); add('×'); add('⊗'); add('â‹…'); add('·'); - }} - ); - put - ( - Operations.Division, new ArrayList() - {{ - add('/'); add('â„'); add('÷'); - //add('/'); add('∕'); add('â„'); add('÷'); add('|'); add('\\'); - }} - ); - } - } - }; - - UnitParseIgnored = new ArrayList() - {{ - add("."); add(","); add(":"); add(";"); add("_"); add("^"); add("+"); - add("#"); add("("); add(")"); add("["); add("]"); add("{"); add("}"); - add("="); add("!"); add("?"); add("@"); add("&"); - }}; - - return ""; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/bb/70aa265dc44a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/bb/70aa265dc44a00171634abff01ee97d5 deleted file mode 100644 index f5a337f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/bb/70aa265dc44a00171634abff01ee97d5 +++ /dev/null @@ -1,21 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - - //new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits); - - //UnitP test = UnitP.Division - //( - // new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - // new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - //); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/bc/809abd317a4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/bc/809abd317a4c00171945f16efe0d9b5d deleted file mode 100644 index a4bd298..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/bc/809abd317a4c00171945f16efe0d9b5d +++ /dev/null @@ -1,626 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -/** -Class including the main hardcoded resources used for internal purposes. -In the original C# code, all this is stored in different files in the Keywords/Private folder. -**/ -@SuppressWarnings("serial") -public class HCUnits -{ - /** - Relates the primary string representations (constants in the UnitSymbols class) with the corresponding - unit (element of the Units enum). - **/ - public static HashMap AllUnitSymbols; - - /**Includes all the units with compound (= dividable by default) types which cannot be divided.**/ - public static ArrayList AllNonDividableUnits; - - /**English-system units which are identical in both Imperial and USCS.**/ - public static ArrayList AllImperialAndUSCSUnits; - - public static void Start() - { - AllUnitSymbols = new HashMap() - { - //--- Unitless - { put("unitless", Units.Unitless); } - - //--- Length - { put(UnitSymbols.Metre, Units.Metre); } - { put(UnitSymbols.Centimetre, Units.Centimetre); } - { put(UnitSymbols.AstronomicalUnit, Units.AstronomicalUnit); } - { put(UnitSymbols.Inch, Units.Inch); } - { put(UnitSymbols.Foot, Units.Foot); } - { put(UnitSymbols.Yard, Units.Yard); } - { put(UnitSymbols.Mile, Units.Mile); } - { put(UnitSymbols.NauticalMile, Units.NauticalMile); } - { put(UnitSymbols.Thou, Units.Thou); } - { put(UnitSymbols.Mil, Units.Mil); } - { put(UnitSymbols.Fathom, Units.Fathom); } - { put(UnitSymbols.Rod, Units.Rod); } - { put(UnitSymbols.Perch, Units.Perch); } - { put(UnitSymbols.Pole, Units.Pole); } - { put(UnitSymbols.Chain, Units.Chain); } - { put(UnitSymbols.Furlong, Units.Furlong); } - { put(UnitSymbols.SurveyInch, Units.SurveyInch); } - { put(UnitSymbols.SurveyFoot, Units.SurveyFoot); } - { put(UnitSymbols.SurveyYard, Units.SurveyYard); } - { put(UnitSymbols.SurveyRod, Units.SurveyRod); } - { put(UnitSymbols.SurveyChain, Units.SurveyChain); } - { put(UnitSymbols.SurveyLink, Units.SurveyLink); } - { put(UnitSymbols.SurveyMile, Units.SurveyMile); } - { put(UnitSymbols.SurveyFathom, Units.SurveyFathom); } - { put(UnitSymbols.Link, Units.Link); } - { put(UnitSymbols.Angstrom, Units.Angstrom); } - { put(UnitSymbols.Fermi, Units.Fermi); } - { put(UnitSymbols.LightYear, Units.LightYear); } - { put(UnitSymbols.Parsec, Units.Parsec); } - { put(UnitSymbols.Micron, Units.Micron); } - - //--- Mass - { put(UnitSymbols.Gram, Units.Gram); } - { put(UnitSymbols.MetricTon, Units.MetricTon); } - { put(UnitSymbols.Grain, Units.Grain); } - { put(UnitSymbols.Drachm, Units.Drachm); } - { put(UnitSymbols.Ounce, Units.Ounce); } - { put(UnitSymbols.Pound, Units.Pound); } - { put(UnitSymbols.Stone, Units.Stone); } - { put(UnitSymbols.Slug, Units.Slug); } - { put(UnitSymbols.Quarter, Units.Quarter); } - { put(UnitSymbols.LongQuarter, Units.LongQuarter); } - { put(UnitSymbols.ShortQuarter, Units.ShortQuarter); } - { put(UnitSymbols.Hundredweight, Units.Hundredweight); } - { put(UnitSymbols.LongHundredweight, Units.LongHundredweight); } - { put(UnitSymbols.ShortHundredweight, Units.ShortHundredweight); } - { put(UnitSymbols.Ton, Units.Ton); } - { put(UnitSymbols.LongTon, Units.LongTon); } - { put(UnitSymbols.ShortTon, Units.ShortTon); } - { put(UnitSymbols.Carat, Units.Carat); } - { put(UnitSymbols.Dalton, Units.Dalton); } - { put(UnitSymbols.UnifiedAtomicMassUnit, Units.UnifiedAtomicMassUnit); } - - //--- Time - { put(UnitSymbols.Second, Units.Second); } - { put(UnitSymbols.Minute, Units.Minute); } - { put(UnitSymbols.Hour, Units.Hour); } - { put(UnitSymbols.Day, Units.Day); } - { put(UnitSymbols.Shake, Units.Shake); } - - //--- Area - { put(UnitSymbols.SquareMetre, Units.SquareMetre); } - { put(UnitSymbols.SquareCentimetre, Units.SquareCentimetre); } - { put(UnitSymbols.Are, Units.Are); } - { put(UnitSymbols.SquareFoot, Units.SquareFoot); } - { put(UnitSymbols.SquareInch, Units.SquareInch); } - { put(UnitSymbols.SquareRod, Units.SquareRod); } - { put(UnitSymbols.SquarePerch, Units.SquarePerch); } - { put(UnitSymbols.SquarePole, Units.SquarePole); } - { put(UnitSymbols.Rood, Units.Rood); } - { put(UnitSymbols.Acre, Units.Acre); } - { put(UnitSymbols.SurveyAcre, Units.SurveyAcre); } - { put(UnitSymbols.Barn, Units.Barn); } - - //--- Volume - { put(UnitSymbols.CubicMetre, Units.CubicMetre); } - { put(UnitSymbols.CubicCentimetre, Units.CubicCentimetre); } - { put(UnitSymbols.Litre, Units.Litre); } - { put(UnitSymbols.CubicFoot, Units.CubicFoot); } - { put(UnitSymbols.CubicInch, Units.CubicInch); } - { put(UnitSymbols.FluidOunce, Units.FluidOunce); } - { put(UnitSymbols.ImperialFluidOunce, Units.ImperialFluidOunce); } - { put(UnitSymbols.USCSFluidOunce, Units.USCSFluidOunce); } - { put(UnitSymbols.Gill, Units.Gill); } - { put(UnitSymbols.ImperialGill, Units.ImperialGill); } - { put(UnitSymbols.USCSGill, Units.USCSGill); } - { put(UnitSymbols.Pint, Units.Pint); } - { put(UnitSymbols.ImperialPint, Units.ImperialPint); } - { put(UnitSymbols.LiquidPint, Units.LiquidPint); } - { put(UnitSymbols.DryPint, Units.DryPint); } - { put(UnitSymbols.Quart, Units.Quart); } - { put(UnitSymbols.ImperialQuart, Units.ImperialQuart); } - { put(UnitSymbols.LiquidQuart, Units.LiquidQuart); } - { put(UnitSymbols.DryQuart, Units.DryQuart); } - { put(UnitSymbols.Gallon, Units.Gallon); } - { put(UnitSymbols.ImperialGallon, Units.ImperialGallon); } - { put(UnitSymbols.LiquidGallon, Units.LiquidGallon); } - { put(UnitSymbols.DryGallon, Units.DryGallon); } - - //--- Angle - { put(UnitSymbols.Radian, Units.Radian); } - { put(UnitSymbols.Degree, Units.Degree); } - { put(UnitSymbols.Arcminute, Units.Arcminute); } - { put(UnitSymbols.Arcsecond, Units.Arcsecond); } - { put(UnitSymbols.Revolution, Units.Revolution); } - { put(UnitSymbols.Gradian, Units.Gradian); } - { put(UnitSymbols.Gon, Units.Gon); } - - //--- Information - { put(UnitSymbols.Bit, Units.Bit); } - { put(UnitSymbols.Byte, Units.Byte); } - { put(UnitSymbols.Nibble, Units.Nibble); } - { put(UnitSymbols.Quartet, Units.Quartet); } - { put(UnitSymbols.Octet, Units.Octet); } - - //--- Force - { put(UnitSymbols.Newton, Units.Newton); } - { put(UnitSymbols.Kilopond, Units.Kilopond); } - { put(UnitSymbols.PoundForce, Units.PoundForce); } - { put(UnitSymbols.Kip, Units.Kip); } - { put(UnitSymbols.Poundal, Units.Poundal); } - { put(UnitSymbols.OunceForce, Units.OunceForce); } - { put(UnitSymbols.Dyne, Units.Dyne); } - - //--- Velocity - { put(UnitSymbols.MetrePerSecond, Units.MetrePerSecond); } - { put(UnitSymbols.CentimetrePerSecond, Units.CentimetrePerSecond); } - { put(UnitSymbols.FootPerSecond, Units.FootPerSecond); } - { put(UnitSymbols.InchPerSecond, Units.InchPerSecond); } - { put(UnitSymbols.Knot, Units.Knot); } - { put(UnitSymbols.KilometrePerHour, Units.KilometrePerHour); } - { put(UnitSymbols.MilePerHour, Units.MilePerHour); } - - //--- Acceleration - { put(UnitSymbols.MetrePerSquareSecond, Units.MetrePerSquareSecond); } - { put(UnitSymbols.Gal, Units.Gal); } - { put(UnitSymbols.FootPerSquareSecond, Units.FootPerSquareSecond); } - { put(UnitSymbols.InchPerSquareSecond, Units.InchPerSquareSecond); } - - //--- Energy - { put(UnitSymbols.Joule, Units.Joule); } - { put(UnitSymbols.Electronvolt, Units.Electronvolt); } - { put(UnitSymbols.WattHour, Units.WattHour); } - { put(UnitSymbols.BritishThermalUnit, Units.BritishThermalUnit); } - { put(UnitSymbols.ThermochemicalBritishThermalUnit, Units.ThermochemicalBritishThermalUnit); } - { put(UnitSymbols.Calorie, Units.Calorie); } - { put(UnitSymbols.ThermochemicalCalorie, Units.ThermochemicalCalorie); } - { put(UnitSymbols.FoodCalorie, Units.FoodCalorie); } - { put(UnitSymbols.Erg, Units.Erg); } - { put(UnitSymbols.Therm, Units.Therm); } - { put(UnitSymbols.UKTherm, Units.UKTherm); } - { put(UnitSymbols.USTherm, Units.USTherm); } - - //--- Power - { put(UnitSymbols.Watt, Units.Watt); } - { put(UnitSymbols.ErgPerSecond, Units.ErgPerSecond); } - { put(UnitSymbols.Horsepower, Units.Horsepower); } - { put(UnitSymbols.MetricHorsepower, Units.MetricHorsepower); } - { put(UnitSymbols.BoilerHorsepower, Units.BoilerHorsepower); } - { put(UnitSymbols.ElectricHorsepower, Units.ElectricHorsepower); } - { put(UnitSymbols.TonOfRefrigeration, Units.TonOfRefrigeration); } - - //--- Pressure - { put(UnitSymbols.Pascal, Units.Pascal); } - { put(UnitSymbols.Atmosphere, Units.Atmosphere); } - { put(UnitSymbols.TechnicalAtmosphere, Units.TechnicalAtmosphere); } - { put(UnitSymbols.Bar, Units.Bar); } - { put(UnitSymbols.PoundforcePerSquareInch, Units.PoundforcePerSquareInch); } - { put(UnitSymbols.PoundforcePerSquareFoot, Units.PoundforcePerSquareFoot); } - { put(UnitSymbols.MillimetreOfMercury, Units.MillimetreOfMercury); } - { put(UnitSymbols.InchOfMercury32F, Units.InchOfMercury32F); } - { put(UnitSymbols.InchOfMercury60F, Units.InchOfMercury60F); } - { put(UnitSymbols.Barye, Units.Barye); } - { put(UnitSymbols.Torr, Units.Torr); } - { put(UnitSymbols.KipPerSquareInch, Units.KipPerSquareInch); } - - //--- Frequency - { put(UnitSymbols.Hertz, Units.Hertz); } - { put(UnitSymbols.CyclePerSecond, Units.CyclePerSecond); } - - //--- Electric Charge - { put(UnitSymbols.Coulomb, Units.Coulomb); } - { put(UnitSymbols.AmpereHour, Units.AmpereHour); } - { put(UnitSymbols.Franklin, Units.Franklin); } - { put(UnitSymbols.Statcoulomb, Units.Statcoulomb); } - { put(UnitSymbols.ESUOfCharge, Units.ESUOfCharge); } - { put(UnitSymbols.Abcoulomb, Units.Abcoulomb); } - { put(UnitSymbols.EMUOfCharge, Units.EMUOfCharge); } - - //--- Electric Current - { put(UnitSymbols.Ampere, Units.Ampere); } - { put(UnitSymbols.Statampere, Units.Statampere); } - { put(UnitSymbols.ESUOfCurrent, Units.ESUOfCurrent); } - { put(UnitSymbols.Abampere, Units.Abampere); } - { put(UnitSymbols.EMUOfCurrent, Units.EMUOfCurrent); } - { put(UnitSymbols.Biot, Units.Biot); } - - //--- Electric Voltage - { put(UnitSymbols.Volt, Units.Volt); } - { put(UnitSymbols.Statvolt, Units.Statvolt); } - { put(UnitSymbols.ESUOfElectricPotential, Units.ESUOfElectricPotential); } - { put(UnitSymbols.Abvolt, Units.Abvolt); } - { put(UnitSymbols.EMUOfElectricPotential, Units.EMUOfElectricPotential); } - - //--- Electric Resistance - { put(UnitSymbols.Ohm, Units.Ohm); } - { put(UnitSymbols.Statohm, Units.Statohm); } - { put(UnitSymbols.ESUOfResistance, Units.ESUOfResistance); } - { put(UnitSymbols.Abohm, Units.Abohm); } - { put(UnitSymbols.EMUOfResistance, Units.EMUOfResistance); } - - //--- Electric Resistivity - { put(UnitSymbols.OhmMetre, Units.OhmMetre); } - - //--- Electric Conductance - { put(UnitSymbols.Siemens, Units.Siemens); } - { put(UnitSymbols.Mho, Units.Mho); } - { put(UnitSymbols.Gemmho, Units.Gemmho); } - { put(UnitSymbols.Statsiemens, Units.Statsiemens); } - { put(UnitSymbols.Statmho, Units.Statmho); } - { put(UnitSymbols.Absiemens, Units.Absiemens); } - { put(UnitSymbols.Abmho, Units.Abmho); } - - //--- Electric Conductivity - { put(UnitSymbols.SiemensPerMetre, Units.SiemensPerMetre); } - - //--- Electric Capacitance - { put(UnitSymbols.Farad, Units.Farad); } - { put(UnitSymbols.Statfarad, Units.Statfarad); } - { put(UnitSymbols.ESUOfCapacitance, Units.ESUOfCapacitance); } - { put(UnitSymbols.Abfarad, Units.Abfarad); } - { put(UnitSymbols.EMUOfCapacitance, Units.EMUOfCapacitance); } - - //--- Electric Inductance - { put(UnitSymbols.Henry, Units.Henry); } - { put(UnitSymbols.Stathenry, Units.Stathenry); } - { put(UnitSymbols.ESUOfInductance, Units.ESUOfInductance); } - { put(UnitSymbols.Abhenry, Units.Abhenry); } - { put(UnitSymbols.EMUOfInductance, Units.EMUOfInductance); } - - //--- Electric Dipole Moment - { put(UnitSymbols.CoulombMetre, Units.CoulombMetre); } - { put(UnitSymbols.Debye, Units.Debye); } - - //--- Temperature - { put(UnitSymbols.Kelvin, Units.Kelvin); } - { put(UnitSymbols.DegreeCelsius, Units.DegreeCelsius); } - { put(UnitSymbols.DegreeFahrenheit, Units.DegreeFahrenheit); } - { put(UnitSymbols.DegreeRankine, Units.DegreeRankine); } - - //--- Wavenumber - { put(UnitSymbols.ReciprocalMetre, Units.ReciprocalMetre); } - { put(UnitSymbols.Kayser, Units.Kayser); } - - //--- Viscosity - { put(UnitSymbols.PascalSecond, Units.PascalSecond); } - { put(UnitSymbols.Poise, Units.Poise); } - - //--- Kinematic Viscosity - { put(UnitSymbols.SquareMetrePerSecond, Units.SquareMetrePerSecond); } - { put(UnitSymbols.Stokes, Units.Stokes); } - - //--- Amount of Substance - { put(UnitSymbols.Mole, Units.Mole); } - { put(UnitSymbols.PoundMole, Units.PoundMole); } - - //--- Momentum - { put(UnitSymbols.NewtonSecond, Units.NewtonSecond); } - - //--- Angular Velocity - { put(UnitSymbols.RadianPerSecond, Units.RadianPerSecond); } - { put(UnitSymbols.RevolutionPerMinute, Units.RevolutionPerMinute); } - - //--- Angular Acceleration - { put(UnitSymbols.RadianPerSquareSecond, Units.RadianPerSquareSecond); } - - //--- Angular Momentum - { put(UnitSymbols.JouleSecond, Units.JouleSecond); } - - //--- Moment of Inertia - { put(UnitSymbols.KilogramSquareMetre, Units.KilogramSquareMetre); } - - //--- Solid Angle - { put(UnitSymbols.Steradian, Units.Steradian); } - { put(UnitSymbols.SquareDegree, Units.SquareDegree); } - - //--- Luminous Intensity - { put(UnitSymbols.Candela, Units.Candela); } - - //--- Luminous Flux - { put(UnitSymbols.Lumen, Units.Lumen); } - - //--- Luminous Energy - { put(UnitSymbols.LumenSecond, Units.LumenSecond); } - { put(UnitSymbols.Talbot, Units.Talbot); } - - //--- Luminance - { put(UnitSymbols.CandelaPerSquareMetre, Units.CandelaPerSquareMetre); } - { put(UnitSymbols.Nit, Units.Nit); } - { put(UnitSymbols.Stilb, Units.Stilb); } - { put(UnitSymbols.Lambert, Units.Lambert); } - { put(UnitSymbols.FootLambert, Units.FootLambert); } - - //--- Illuminance - { put(UnitSymbols.Lux, Units.Lux); } - { put(UnitSymbols.Phot, Units.Phot); } - { put(UnitSymbols.FootCandle, Units.FootCandle); } - - //--- Logarithmic - { put(UnitSymbols.Bel, Units.Bel); } - { put(UnitSymbols.Neper, Units.Neper); } - - //--- Magnetic Flux - { put(UnitSymbols.Weber, Units.Weber); } - { put(UnitSymbols.Maxwell, Units.Maxwell); } - - //--- Magnetic Field B - { put(UnitSymbols.Tesla, Units.Tesla); } - { put(UnitSymbols.Gauss, Units.Gauss); } - - //--- Magnetic Field H - { put(UnitSymbols.AmperePerMetre, Units.AmperePerMetre); } - { put(UnitSymbols.Oersted, Units.Oersted); } - - //--- Radioactivity - { put(UnitSymbols.Becquerel, Units.Becquerel); } - { put(UnitSymbols.Curie, Units.Curie); } - { put(UnitSymbols.DisintegrationsPerSecond, Units.DisintegrationsPerSecond); } - { put(UnitSymbols.DisintegrationsPerMinute, Units.DisintegrationsPerMinute); } - { put(UnitSymbols.Rutherford, Units.Rutherford); } - - //--- Absorbed Dose - { put(UnitSymbols.Gray, Units.Gray); } - { put(UnitSymbols.Rad, Units.Rad); } - - //--- Absorbed Dose Rate - { put(UnitSymbols.GrayPerSecond, Units.GrayPerSecond); } - - //--- Equivalent Dose - { put(UnitSymbols.Sievert, Units.Sievert); } - { put(UnitSymbols.REM, Units.REM); } - - //--- Exposure - { put(UnitSymbols.CoulombPerKilogram, Units.CoulombPerKilogram); } - { put(UnitSymbols.Roentgen, Units.Roentgen); } - - //--- Catalytic Activity - { put(UnitSymbols.Katal, Units.Katal); } - - //--- Catalytic Activity Concentration - { put(UnitSymbols.KatalPerCubicMetre, Units.KatalPerCubicMetre); } - - //--- Jerk - { put(UnitSymbols.MetrePerCubicSecond, Units.MetrePerCubicSecond); } - - //--- Mass Flow Rate - { put(UnitSymbols.KilogramPerSecond, Units.KilogramPerSecond); } - - //--- Density - { put(UnitSymbols.KilogramPerCubicMetre, Units.KilogramPerCubicMetre); } - - //--- Area Density - { put(UnitSymbols.KilogramPerSquareMetre, Units.KilogramPerSquareMetre); } - - //--- Energy Density - { put(UnitSymbols.JoulePerCubicMetre, Units.JoulePerCubicMetre); } - - //--- Specific Volume - { put(UnitSymbols.CubicMetrePerKilogram, Units.CubicMetrePerKilogram); } - - //--- Volumetric Flow Rate - { put(UnitSymbols.CubicMetrePerSecond, Units.CubicMetrePerSecond); } - - //--- Surface Tension - { put(UnitSymbols.JoulePerSquareMetre, Units.JoulePerSquareMetre); } - - //--- Specific Weight - { put(UnitSymbols.NewtonPerCubicMetre, Units.NewtonPerCubicMetre); } - - //--- Thermal Conductivity - { put(UnitSymbols.WattPerMetrePerKelvin, Units.WattPerMetrePerKelvin); } - - //--- Thermal Conductance - { put(UnitSymbols.WattPerKelvin, Units.WattPerKelvin); } - - //--- Thermal Resistivity - { put(UnitSymbols.MetreKelvinPerWatt, Units.MetreKelvinPerWatt); } - - //--- Thermal Resistance - { put(UnitSymbols.KelvinPerWatt, Units.KelvinPerWatt); } - - //--- Heat Transfer Coefficient - { put(UnitSymbols.WattPerSquareMetrePerKelvin, Units.WattPerSquareMetrePerKelvin); } - - //--- Heat Flux Density - { put(UnitSymbols.WattPerSquareMetre, Units.WattPerSquareMetre); } - - //--- Entropy - { put(UnitSymbols.JoulePerKelvin, Units.JoulePerKelvin); } - - //--- Electric Field Strength - { put(UnitSymbols.NewtonPerCoulomb, Units.NewtonPerCoulomb); } - { put(UnitSymbols.VoltPerMetre, Units.VoltPerMetre); } - - //--- Linear Electric Charge Density - { put(UnitSymbols.CoulombPerMetre, Units.CoulombPerMetre); } - - //--- Surface Electric Charge Density - { put(UnitSymbols.CoulombPerSquareMetre, Units.CoulombPerSquareMetre); } - - //--- Volume Electric Charge Density - { put(UnitSymbols.CoulombPerCubicMetre, Units.CoulombPerCubicMetre); } - - //--- Current Density - { put(UnitSymbols.AmperePerSquareMetre, Units.AmperePerSquareMetre); } - - //--- Electromagnetic Permittivity - { put(UnitSymbols.FaradPerMetre, Units.FaradPerMetre); } - - //--- Electromagnetic Permeability - { put(UnitSymbols.HenryPerMetre, Units.HenryPerMetre); } - - //--- Molar Energy - { put(UnitSymbols.JoulePerMole, Units.JoulePerMole); } - - //--- Molar Entropy - { put(UnitSymbols.JoulePerMolePerKelvin, Units.JoulePerMolePerKelvin); } - - //--- Molar Volume - { put(UnitSymbols.CubicMetrePerMole, Units.CubicMetrePerMole); } - - //--- Molar Mass - { put(UnitSymbols.KilogramPerMole, Units.KilogramPerMole); } - - //--- Molar Concentration - { put(UnitSymbols.MolePerCubicMetre, Units.MolePerCubicMetre); } - - //--- Molal Concentration - { put(UnitSymbols.MolePerKilogram, Units.MolePerKilogram); } - - //--- Radiant Intensity - { put(UnitSymbols.WattPerSteradian, Units.WattPerSteradian); } - - //--- Radiance - { put(UnitSymbols.WattPerSteradianPerSquareMetre, Units.WattPerSteradianPerSquareMetre); } - - //--- Fuel Economy - { put(UnitSymbols.InverseSquareMetre, Units.InverseSquareMetre); } - { put(UnitSymbols.MilePerGallon, Units.MilePerGallon); } - { put(UnitSymbols.ImperialMilePerGallon, Units.ImperialMilePerGallon); } - { put(UnitSymbols.USCSMilePerGallon, Units.USCSMilePerGallon); } - { put(UnitSymbols.KilometrePerLitre, Units.KilometrePerLitre); } - - //--- Sound Exposure - { put(UnitSymbols.SquarePascalSecond, Units.SquarePascalSecond); } - - //--- Sound Impedance - { put(UnitSymbols.PascalSecondPerCubicMetre, Units.PascalSecondPerCubicMetre); } - - //--- Rotational Stiffness - { put(UnitSymbols.NewtonMetrePerRadian, Units.NewtonMetrePerRadian); } - - //--- Bit Rate - { put(UnitSymbols.BitPerSecond, Units.BitPerSecond); } - - //--- Symbol Rate - { put(UnitSymbols.Baud, Units.Baud); } - }; - - AllNonDividableUnits = new ArrayList() - {{ - //--- Area - add(Units.Are); add(Units.Rood); add(Units.Acre); add(Units.Barn); add(Units.SurveyAcre); - - //--- Volume - add(Units.Litre); add(Units.FluidOunce); add(Units.ImperialFluidOunce); add(Units.USCSFluidOunce); add(Units.Gill); - add(Units.ImperialGill); add(Units.USCSGill); add(Units.Pint); add(Units.ImperialPint); add(Units.LiquidPint); - add(Units.DryPint); add(Units.Quart); add(Units.ImperialQuart); add(Units.LiquidQuart); add(Units.DryQuart); - add(Units.Gallon); add(Units.ImperialGallon); add(Units.LiquidGallon); add(Units.DryGallon); - - //--- Force - add(Units.Kilopond); add(Units.PoundForce); add(Units.Kip); add(Units.OunceForce); - - //--- Energy - add(Units.Electronvolt); add(Units.BritishThermalUnit); add(Units.ThermochemicalBritishThermalUnit); - add(Units.Calorie); add(Units.ThermochemicalCalorie); add(Units.FoodCalorie); add(Units.Therm); add(Units.UKTherm); - add(Units.USTherm); - - //--- Power - add(Units.Horsepower); add(Units.MetricHorsepower); add(Units.BoilerHorsepower); add(Units.ElectricHorsepower); - add(Units.TonOfRefrigeration); - - //--- Pressure - add(Units.Atmosphere); add(Units.TechnicalAtmosphere); add(Units.Bar); add(Units.MillimetreOfMercury); add(Units.InchOfMercury32F); - add(Units.InchOfMercury60F); add(Units.Torr); - - //--- Amount of substance - add(Units.PoundMole); - - //Note that all the electricity/magnetism CGS compounds are considered non-dividable. - //This is because of its multi-system peculiarities and what it entails. - //These are old units where the dividable-compound icing isn't expected to be that important. - //Compounds which might be defined without a direct reliance on electricity/magnetism units are - //dividable. For example, G (= Mx/cm2). - - //--- Electric Charge - add(Units.Franklin); add(Units.Statcoulomb); add(Units.ESUOfCharge); add(Units.Abcoulomb); add(Units.EMUOfCharge); - - //--- Electric Voltage - add(Units.ESUOfElectricPotential); add(Units.Statvolt); add(Units.EMUOfElectricPotential); add(Units.Abvolt); - - //--- Electric Resistance - add(Units.Statohm); add(Units.ESUOfResistance); add(Units.Abohm); add(Units.EMUOfResistance); - - //--- Electric Conductance - add(Units.Gemmho); add(Units.Statsiemens); add(Units.Statmho); add(Units.Absiemens); add(Units.Abmho); - - //--- Electric Capacitance - add(Units.Statfarad); add(Units.ESUOfCapacitance); add(Units.Abfarad); add(Units.EMUOfCapacitance); - - //--- Electric Inductance - add(Units.Stathenry); add(Units.ESUOfInductance); add(Units.Abhenry); add(Units.EMUOfInductance); - - //--- Electric Dipole Moment - add(Units.Debye); - - //--- Luminance - add(Units.Lambert); add(Units.FootLambert); - - //--- Magnetic Flux - add(Units.Maxwell); - - //--- Magnetic Field H - add(Units.Oersted); - - //--- Absorbed Dose - add(Units.Rad); - - //--- Equivalent Dose - add(Units.REM); - - //--- Exposure - add(Units.Roentgen); - }}; - - AllImperialAndUSCSUnits = new ArrayList() - {{ - //--- Length - add(Units.Inch); add(Units.Foot); add(Units.Yard); add(Units.Mile); add(Units.Thou); - add(Units.Mil); add(Units.Fathom); add(Units.Rod); add(Units.Perch); add(Units.Pole); - add(Units.Chain); add(Units.Furlong); add(Units.Link); - - //--- Mass - add(Units.Grain); add(Units.Drachm); add(Units.Ounce); add(Units.Pound); add(Units.Stone); - add(Units.Slug); - - //--- Area - add(Units.SquareInch); add(Units.SquareFoot); add(Units.SquareRod); add(Units.SquarePerch); - add(Units.SquarePole); add(Units.Rood); add(Units.Acre); - - //--- Volume - add(Units.CubicInch); add(Units.CubicFoot); - - //--- Force - add(Units.PoundForce); add(Units.Poundal); add(Units.OunceForce); - - //--- Velocity - add(Units.FootPerSecond); add(Units.InchPerSecond); add(Units.MilePerHour); - - //--- Acceleration - add(Units.FootPerSquareSecond); add(Units.InchPerSquareSecond); - - //--- Energy - add(Units.BritishThermalUnit); add(Units.ThermochemicalBritishThermalUnit); - - //--- Power - add(Units.Horsepower); - - //--- Pressure - add(Units.PoundforcePerSquareInch); add(Units.PoundforcePerSquareFoot); - - //--- Temperature - add(Units.DegreeFahrenheit); add(Units.DegreeRankine); - - //--- Luminance - add(Units.FootLambert); - - //--- Illuminance - add(Units.FootCandle); - }}; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/be/c0c1d6019a4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/be/c0c1d6019a4a00171930ee4d171ed0de deleted file mode 100644 index 8e76e93..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/be/c0c1d6019a4a00171930ee4d171ed0de +++ /dev/null @@ -1,1032 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/be/d036f0c8504c00171860ae6a5189088d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/be/d036f0c8504c00171860ae6a5189088d deleted file mode 100644 index cc47318..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/be/d036f0c8504c00171860ae6a5189088d +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - System.out.println(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/bf/203990246c4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/bf/203990246c4c00171838d4a3813404a0 deleted file mode 100644 index b9d6fc7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/bf/203990246c4c00171838d4a3813404a0 +++ /dev/null @@ -1,271 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - X output = null; - try - { - output = GetFirst - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return output; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal, ExceptionTypes type) throws Exception - { - if (input == null) - { - return GetDefaultOrException(defaultVal, type); - } - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return GetDefaultOrException(defaultVal, type); - } - - private static X GetDefaultOrException(X defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = input; - if (filter != null) - { - tempVar = WhereDict(input, filter); - } - if (tempVar == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(tempVar), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/10f7916c944a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/10f7916c944a00171930ee4d171ed0de deleted file mode 100644 index d931255..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/10f7916c944a00171930ee4d171ed0de +++ /dev/null @@ -1,567 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - System.out.println(output.Value + " " + output.BaseTenExponent + " " + output.Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/20cb78d0634c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/20cb78d0634c0017146ede6da4ae5d42 deleted file mode 100644 index 78e4c53..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/20cb78d0634c0017146ede6da4ae5d42 +++ /dev/null @@ -1,431 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - System.out.println("Condition 1 true"); - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/70b15c7d794c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/70b15c7d794c00171945f16efe0d9b5d deleted file mode 100644 index 7c56a61..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/70b15c7d794c00171945f16efe0d9b5d +++ /dev/null @@ -1,254 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return 0; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || input.entrySet() == null || filter == null) - { - return new ArrayList(); - } - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.entrySet() == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/f005907d964a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/f005907d964a00171930ee4d171ed0de deleted file mode 100644 index 866f45e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c0/f005907d964a00171930ee4d171ed0de +++ /dev/null @@ -1,574 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - System.out.println(big2.Value); - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - System.out.println(output.BaseTenExponent); - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c1/c0d8268b6b4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c1/c0d8268b6b4c00171838d4a3813404a0 deleted file mode 100644 index 1f9cd3c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c1/c0d8268b6b4c00171838d4a3813404a0 +++ /dev/null @@ -1,329 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - X output = null; - try - { - output = GetFirst - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return output; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal, ExceptionTypes type) throws Exception - { - if (input == null) - { - return GetDefaultOrException(defaultVal, type); - } - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return GetDefaultOrException(defaultVal, type); - } - - private static X GetDefaultOrException(X defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - public static Map.Entry FirstDict(HashMap input) throws Exception - { - return FirstDict(input, null); - } - - public static Map.Entry FirstDict(HashMap input, Predicate> filter) throws Exception - { - if (filter != null) input = WhereDict(input, filter); - - return GetFirstDict - ( - input, filter, null, ExceptionTypes.FirstDict - ); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - HashMap tempVar = input; - if (filter != null) - { - tempVar = WhereDict(input, filter); - } - if (tempVar == null) return defaultVal; - - HashMap input2 = new HashMap(tempVar); - - try - { - return GetFirstDict - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return defaultVal; - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return null; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal, ExceptionTypes type - ) - throws Exception - { - if (input == null) - { - return GetDefaultOrExceptionDict(defaultVal, type); - } - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return GetDefaultOrExceptionDict(defaultVal, type); - } - - private static Map.Entry GetDefaultOrExceptionDict(Map.Entry defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - private static void ThrowException(ExceptionTypes type) throws Exception - { - String method = "First"; - if (type == ExceptionTypes.FirstDict) - { - method = " (1-D collections)"; - } - else if (type == ExceptionTypes.First) - { - method = " (dictionaries)"; - } - - throw new Exception("Exception provoked by an error in the custom version of the " + method + " LINQ method."); - } - - enum ExceptionTypes { None, First, FirstDict } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c2/40ea113a404c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c2/40ea113a404c00171eb8e3cba3fc21fa deleted file mode 100644 index 8586c47..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c2/40ea113a404c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,68 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //Emulating the conditions of the original C# version where decimal numbers cannot be parsed as integer. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input) throws ParseException - { - //Locale.US because of being the best equivalence for CultureInfo.InvariantCulture in the original C# code. - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c2/d035ba8cb14a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c2/d035ba8cb14a00171059ebc16969059f deleted file mode 100644 index 56f022c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c2/d035ba8cb14a00171059ebc16969059f +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - System.out.println(convFactor.Value); - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c3/80c1169f2a4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c3/80c1169f2a4a001712d4a4f7b050cac8 deleted file mode 100644 index abcbe8a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c3/80c1169f2a4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1164 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - System.out.println("asfasf"); - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c4/500350c89c4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c4/500350c89c4a00171930ee4d171ed0de deleted file mode 100644 index 606a332..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c4/500350c89c4a00171930ee4d171ed0de +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - //System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c4/808a7e97404c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c4/808a7e97404c00171eb8e3cba3fc21fa deleted file mode 100644 index aea2699..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c4/808a7e97404c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,19 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test0 = new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits); - //System.out.println(test0.ValueAndUnitString); - UnitP test = UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c5/404943d5a74a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c5/404943d5a74a00171059ebc16969059f deleted file mode 100644 index 5037051..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c5/404943d5a74a00171059ebc16969059f +++ /dev/null @@ -1,13 +0,0 @@ -package test0; - -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP(1.0, Units.Metre); //UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft")); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c5/d0694da42d4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c5/d0694da42d4a001712d4a4f7b050cac8 deleted file mode 100644 index c8a6212..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c5/d0694da42d4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1032 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); -System.out.println("asfasdf"); - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/40f02cf09c4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/40f02cf09c4a00171930ee4d171ed0de deleted file mode 100644 index 77fa7b7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/40f02cf09c4a00171930ee4d171ed0de +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/b021b8ad5b4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/b021b8ad5b4c0017146ede6da4ae5d42 deleted file mode 100644 index 2941c3c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/b021b8ad5b4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,12 +0,0 @@ -package test0; - -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP(1.0, "surin3/in"); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/c05143092d4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/c05143092d4a001712d4a4f7b050cac8 deleted file mode 100644 index 6d50d31..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/c05143092d4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1858 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - System.out.println(outUnitString); - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/f0e01471b14a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/f0e01471b14a00171059ebc16969059f deleted file mode 100644 index 6579a37..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c6/f0e01471b14a00171059ebc16969059f +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - System.out.println(convFactor); - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c7/a0f8ef36b24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c7/a0f8ef36b24a00171059ebc16969059f deleted file mode 100644 index 4077707..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c7/a0f8ef36b24a00171059ebc16969059f +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - System.out.println(outInfo.Value); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c7/d070479b294c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c7/d070479b294c00171ae7fcf2c321c986 deleted file mode 100644 index 21fa583..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c7/d070479b294c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1052 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - System.out.println(tempInfo.Value + " " + tempInfo.BaseTenExponent); - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c8/509495a2b44a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c8/509495a2b44a00171059ebc16969059f deleted file mode 100644 index 145b815..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c8/509495a2b44a00171059ebc16969059f +++ /dev/null @@ -1,336 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -//This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). -//The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - -public class ExceptionInstantiation -{ - public static UnitInfo NewUnitInfo() - { - UnitInfo output = null; - - try - { - output = new UnitInfo(); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, int baseTenExponent) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value, baseTenExponent); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(Units unit) - { - return NewUnitInfo(unit, 1.0); - } - - public static UnitInfo NewUnitInfo(Units unit, double factor) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unit, factor); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, Units unit, Prefix prefix) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value, unit, prefix); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value) - { - return NewUnitInfo(value, null); - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value, exceptionHandling, prefixUsage); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, ArrayList parts) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value); - - if (parts != null) - { - output.Parts = new ArrayList(parts); - } - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(ArrayList parts) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(); - output.Parts = new ArrayList(parts); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, double value) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Value = value; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, ErrorTypes errorType) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Error = new ErrorInfo(errorType); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(ErrorTypes errorType) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(); - output.Error = new ErrorInfo(errorType); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, Units unit) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Unit = unit; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, Units unit, double factor) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Unit = unit; - output.Prefix = new Prefix(factor); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, double value, int baseTenExponent) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Value = value; - output.BaseTenExponent = baseTenExponent; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, Prefix prefix) - { - return NewUnitInfo(unitInfo, 0, prefix); - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, int baseTenExponent, Prefix prefix) - { - return NewUnitInfo(unitInfo, 0.0, baseTenExponent, prefix); - } - - public static UnitInfo NewUnitInfo(UnitP unitP, double value, int baseTenExponent, Prefix prefix) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitP); - output.BaseTenExponent = baseTenExponent; - output.Prefix = new Prefix(prefix); - output.Value = value; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, double value, int baseTenExponent, Prefix prefix) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.BaseTenExponent = baseTenExponent; - output.Prefix = new Prefix(prefix); - output.Value = value; - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitInfo unitInfo, Units unit, ArrayList parts) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitInfo); - output.Unit = unit; - output.Parts = new ArrayList(parts); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(double value, Units unit, Prefix prefix, boolean getParts) - { - return NewUnitInfo - ( - value, unit, prefix, getParts, ExceptionHandlingTypes.AlwaysTriggerException - ); - } - - public static UnitInfo NewUnitInfo(double value, Units unit, Prefix prefix, boolean getParts, ExceptionHandlingTypes exceptionHandling) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(value, unit, prefix, getParts, exceptionHandling); - } - catch(Exception e) { } - - return output; - } - - public static UnitInfo NewUnitInfo(UnitP unitP) - { - UnitInfo output = null; - - try - { - output = new UnitInfo(unitP); - } - catch(Exception e) { } - - return output; - } - - public static ErrorInfo NewErrorInfo(ErrorTypes errorType) - { - ErrorInfo output = null; - - try - { - output = new ErrorInfo(errorType); - } - catch(Exception e) { } - - return output; - } - - public static ErrorInfo NewErrorInfo(ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling) - { - ErrorInfo output = null; - - try - { - output = new ErrorInfo(errorType, exceptionHandling); - } - catch(Exception e) { } - - return output; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c9/1012a347f44c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c9/1012a347f44c00171048b3f61ecb42d3 deleted file mode 100644 index 92c773b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c9/1012a347f44c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1224 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c9/a042fb1cb24b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c9/a042fb1cb24b00171c69d98bf667dda6 deleted file mode 100644 index 79e18aa..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c9/a042fb1cb24b00171c69d98bf667dda6 +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c9/e0911e50964a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c9/e0911e50964a00171930ee4d171ed0de deleted file mode 100644 index b0c57f1..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/c9/e0911e50964a00171930ee4d171ed0de +++ /dev/null @@ -1,574 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - System.out.println(big2.Value); - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - System.out.println(output.Value); - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ca/4068b81bf84c001712ece6513f6adb77 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ca/4068b81bf84c001712ece6513f6adb77 deleted file mode 100644 index 0810233..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ca/4068b81bf84c001712ece6513f6adb77 +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ca/d09dc7b7934a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ca/d09dc7b7934a00171930ee4d171ed0de deleted file mode 100644 index 77802d8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ca/d09dc7b7934a00171930ee4d171ed0de +++ /dev/null @@ -1,567 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ca/e096f06ba84a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ca/e096f06ba84a00171059ebc16969059f deleted file mode 100644 index 34ad7ac..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ca/e096f06ba84a00171059ebc16969059f +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/1072ee117a4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/1072ee117a4c00171945f16efe0d9b5d deleted file mode 100644 index 878bc00..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/1072ee117a4c00171945f16efe0d9b5d +++ /dev/null @@ -1,281 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class HCPrefixes -{ - /** - Relates the SI prefixes (SIPrefixes enum) with their values (constants in the SIPrefixValues class). - **/ - public static HashMap AllSIPrefixes; - - //Relates the SI prefix strings (SIPrefixSymbols enum) with their values (constants in the SIPrefixValues class). - public static HashMap AllSIPrefixSymbols; - - //Relates the binary prefixes (BinaryPrefixes enum) with their values (constants in the BinaryPrefixValues class). - public static HashMap AllBinaryPrefixes; - - //Relates the binary prefix strings (BinaryPrefixSymbols enum) with their values (constants in the BinaryPrefixValues class). - public static HashMap AllBinaryPrefixSymbols; - - //Contains all the units outside the SI-prefix-supporting systems (i.e., UnitSystems.SI & UnitSystems.CGS) - //which do support SI prefixes by default. - public static ArrayList AllOtherSIPrefixUnits; - - //By default, global prefixes aren't used with compounds to avoid misunderstandings. For example: 1000 m^2 converted - //into k m^2 confused as km2. This collection includes all the compounds which might use prefixes. - public static ArrayList AllCompoundsUsingPrefixes; - - //Includes all the unit types which support binary prefixes by default. - public static ArrayList AllBinaryPrefixTypes; - - //All the collections below this line are secondary/used for very specific purposes. That's why they - //are only populated when being used for the first time. - - //The full names of all the SI/binary prefixes. - public static HashMap AllSIPrefixNames, AllBinaryPrefixNames; - - //Various collections used in prefix-related calculations. - public static ArrayList BigSIPrefixValues, SmallSIPrefixValues, BigBinaryPrefixValues, SmallBinaryPrefixValues; - - public static void Start() - { - AllBinaryPrefixTypes = new ArrayList() - {{ - add(UnitTypes.Information); add(UnitTypes.BitRate); add(UnitTypes.SymbolRate); - }}; - - AllCompoundsUsingPrefixes = new ArrayList() - {{ - //--- Area - add(Units.Rood); add(Units.Acre); add(Units.SurveyAcre); - - //--- Volume - add(Units.FluidOunce); add(Units.ImperialFluidOunce); add(Units.USCSFluidOunce); add(Units.Gill); - add(Units.ImperialGill); add(Units.USCSGill); add(Units.Pint); add(Units.ImperialPint); add(Units.LiquidPint); - add(Units.DryPint); add(Units.Quart); add(Units.ImperialQuart); add(Units.LiquidQuart); add(Units.DryQuart); - add(Units.Gallon); add(Units.LiquidGallon); add(Units.DryGallon); - - //--- Velocity - add(Units.Knot); - - //--- Acceleration - add(Units.Gal); - - //--- Force - add(Units.Newton); add(Units.Dyne); add(Units.PoundForce); add(Units.Poundal); add(Units.OunceForce); - - //--- Energy - add(Units.Joule); add(Units.Erg); add(Units.WattHour); add(Units.Calorie); add(Units.ThermochemicalCalorie); - add(Units.FoodCalorie); add(Units.BritishThermalUnit); add(Units.ThermochemicalBritishThermalUnit); - add(Units.Therm); add(Units.UKTherm); add(Units.USTherm); - - //--- Power - add(Units.Watt); add(Units.Horsepower); add(Units.MetricHorsepower); add(Units.ElectricHorsepower); - add(Units.BoilerHorsepower); add(Units.TonOfRefrigeration); - - //--- Pressure - add(Units.Pascal); add(Units.Barye); add(Units.Atmosphere); add(Units.TechnicalAtmosphere); add(Units.Bar); - add(Units.Torr); - - //--- Frequency - add(Units.Hertz); - - //--- Electric Charge - add(Units.AmpereHour); - - //--- Electric Current - add(Units.Ampere); add(Units.Statampere); add(Units.Abampere); add(Units.Biot); - - //--- Electric Voltage - add(Units.Volt); add(Units.Statvolt); add(Units.Abvolt); - - //--- Electric Resitance - add(Units.Ohm); add(Units.Statohm); add(Units.Abohm); - - //--- Electric Conductance - add(Units.Siemens); add(Units.Mho); add(Units.Gemmho); add(Units.Statsiemens); add(Units.Statmho); - add(Units.Absiemens); add(Units.Abmho); - - //--- Electric Capacitance - add(Units.Farad); add(Units.Statfarad); add(Units.Abfarad); - - //--- Electric Inductance - add(Units.Henry); add(Units.Stathenry); add(Units.Abhenry); - - //--- Electric Dipole Moment - add(Units.Debye); - - //--- Wavenumber - add(Units.Kayser); - - //--- Viscosity - add(Units.Poise); - - //--- Kinematic Viscosity - add(Units.Stokes); - - //--- Solid Angle - add(Units.Steradian); - - //--- Luminous Flux - add(Units.Lumen); - - //--- Luminous Energy - add(Units.Talbot); - - //--- Luminance - add(Units.Stilb); add(Units.Nit); add(Units.Lambert); add(Units.FootLambert); - - //--- Illuminance - add(Units.Lux); add(Units.Phot); add(Units.FootCandle); - - //--- Magnetic Flux - add(Units.Weber); add(Units.Maxwell); - - //--- Magnetic Field H - add(Units.Oersted); - - //--- Magnetic Field B - add(Units.Tesla); add(Units.Gauss); - - //--- Absorbed Dose - add(Units.Gray); add(Units.Rad); - - //--- Equivalent Dose - add(Units.Sievert); add(Units.REM); - - //--- Exposure - add(Units.Roentgen); - - //--- Catalytic Activity - add(Units.Katal); - - //--- Bit Rate - add(Units.BitPerSecond); - }}; - - AllOtherSIPrefixUnits = new ArrayList() - {{ - //--- Length - add(Units.Parsec); - - //--- Mass - add(Units.MetricTon); add(Units.Dalton); add(Units.UnifiedAtomicMassUnit); - - //--- Area - add(Units.Are); add(Units.Barn); - - //--- Volume - add(Units.Litre); - - //--- Information - add(Units.Bit); add(Units.Byte); add(Units.Nibble); add(Units.Quartet); add(Units.Octet); - - //--- Energy - add(Units.Electronvolt); add(Units.WattHour); add(Units.Calorie); add(Units.ThermochemicalCalorie); - - //--- Pressure - add(Units.Bar); add(Units.Torr); - - //--- Electric Charge - add(Units.AmpereHour); - - //--- Logarithmic - add(Units.Bel); add(Units.Neper); - - //--- Radioactivity - add(Units.Curie); - - //--- Bit Rate - add(Units.BitPerSecond); - - //--- Symbol Rate - add(Units.Baud); - }}; - - AllBinaryPrefixSymbols = new HashMap() - { - { - put(BinaryPrefixSymbols.Kibi, BinaryPrefixValues.Kibi); - put(BinaryPrefixSymbols.Mebi, BinaryPrefixValues.Mebi); - put(BinaryPrefixSymbols.Gibi, BinaryPrefixValues.Gibi); - put(BinaryPrefixSymbols.Tebi, BinaryPrefixValues.Tebi); - put(BinaryPrefixSymbols.Pebi, BinaryPrefixValues.Pebi); - put(BinaryPrefixSymbols.Exbi, BinaryPrefixValues.Exbi); - put(BinaryPrefixSymbols.Zebi, BinaryPrefixValues.Zebi); - put(BinaryPrefixSymbols.Yobi, BinaryPrefixValues.Yobi); - } - }; - - AllBinaryPrefixes = new HashMap() - { - { - put(BinaryPrefixes.Kibi, BinaryPrefixValues.Kibi); - put(BinaryPrefixes.Mebi, BinaryPrefixValues.Mebi); - put(BinaryPrefixes.Gibi, BinaryPrefixValues.Gibi); - put(BinaryPrefixes.Tebi, BinaryPrefixValues.Tebi); - put(BinaryPrefixes.Pebi, BinaryPrefixValues.Pebi); - put(BinaryPrefixes.Exbi, BinaryPrefixValues.Exbi); - put(BinaryPrefixes.Zebi, BinaryPrefixValues.Zebi); - put(BinaryPrefixes.Yobi, BinaryPrefixValues.Yobi); - } - }; - - AllSIPrefixSymbols = new HashMap() - { - { - put(SIPrefixSymbols.Yotta, SIPrefixValues.Yotta); - put(SIPrefixSymbols.Zetta, SIPrefixValues.Zetta); - put(SIPrefixSymbols.Exa, SIPrefixValues.Exa); - put(SIPrefixSymbols.Peta, SIPrefixValues.Peta); - put(SIPrefixSymbols.Tera, SIPrefixValues.Tera); - put(SIPrefixSymbols.Giga, SIPrefixValues.Giga); - put(SIPrefixSymbols.Mega, SIPrefixValues.Mega); - put(SIPrefixSymbols.Kilo, SIPrefixValues.Kilo); - put(SIPrefixSymbols.Hecto, SIPrefixValues.Hecto); - put(SIPrefixSymbols.Deca, SIPrefixValues.Deca); - put(SIPrefixSymbols.Deci, SIPrefixValues.Deci); - put(SIPrefixSymbols.Centi, SIPrefixValues.Centi); - put(SIPrefixSymbols.Milli, SIPrefixValues.Milli); - put(SIPrefixSymbols.Micro, SIPrefixValues.Micro); - put(SIPrefixSymbols.Nano, SIPrefixValues.Nano); - put(SIPrefixSymbols.Pico, SIPrefixValues.Pico); - put(SIPrefixSymbols.Femto, SIPrefixValues.Femto); - put(SIPrefixSymbols.Atto, SIPrefixValues.Atto); - put(SIPrefixSymbols.Zepto, SIPrefixValues.Zepto); - put(SIPrefixSymbols.Yocto, SIPrefixValues.Yocto); - } - }; - - AllSIPrefixes = new HashMap() - { - { - put(SIPrefixes.Yotta, SIPrefixValues.Yotta); - put(SIPrefixes.Zetta, SIPrefixValues.Zetta); - put(SIPrefixes.Exa, SIPrefixValues.Exa); - put(SIPrefixes.Peta, SIPrefixValues.Peta); - put(SIPrefixes.Tera, SIPrefixValues.Tera); - put(SIPrefixes.Giga, SIPrefixValues.Giga); - put(SIPrefixes.Mega, SIPrefixValues.Mega); - put(SIPrefixes.Kilo, SIPrefixValues.Kilo); - put(SIPrefixes.Hecto, SIPrefixValues.Hecto); - put(SIPrefixes.Deca, SIPrefixValues.Deca); - put(SIPrefixes.Deci, SIPrefixValues.Deci); - put(SIPrefixes.Centi, SIPrefixValues.Centi); - put(SIPrefixes.Milli, SIPrefixValues.Milli); - put(SIPrefixes.Micro, SIPrefixValues.Micro); - put(SIPrefixes.Nano, SIPrefixValues.Nano); - put(SIPrefixes.Pico, SIPrefixValues.Pico); - put(SIPrefixes.Femto, SIPrefixValues.Femto); - put(SIPrefixes.Atto, SIPrefixValues.Atto); - put(SIPrefixes.Zepto, SIPrefixValues.Zepto); - put(SIPrefixes.Yocto, SIPrefixValues.Yocto); - } - }; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/408f4224b44a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/408f4224b44a00171059ebc16969059f deleted file mode 100644 index b8ac4f5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/408f4224b44a00171059ebc16969059f +++ /dev/null @@ -1,1062 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - System.out.println(originalInfo.Value + " " + newExponent); - UnitInfo test = Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - System.out.println(test.Value + " asdfasdf"); - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/a0fd6eabae4b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/a0fd6eabae4b00171c69d98bf667dda6 deleted file mode 100644 index 7f421a7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/a0fd6eabae4b00171c69d98bf667dda6 +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - System.out.println(first.Value + " " + first.BaseTenExponent + " " + second.ValueAndUnitString); - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/d0b5993aa94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/d0b5993aa94a00171059ebc16969059f deleted file mode 100644 index c3b395b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cb/d0b5993aa94a00171059ebc16969059f +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - System.out.println(outInfo.Parts.get(0).Unit + " " + outInfo.Parts.get(1).Unit); - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cc/70720151f44c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cc/70720151f44c00171048b3f61ecb42d3 deleted file mode 100644 index 0ee6d19..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cc/70720151f44c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1225 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - @return Current instance including the information resulting from converting unitP to targetUnit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cd/2049d485a94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cd/2049d485a94a00171059ebc16969059f deleted file mode 100644 index 76f8e8c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cd/2049d485a94a00171059ebc16969059f +++ /dev/null @@ -1,1382 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - System.out.println(parseInfo.UnitInfo.System); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cd/601eeb375b4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cd/601eeb375b4c0017146ede6da4ae5d42 deleted file mode 100644 index 33703ff..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cd/601eeb375b4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1197 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - public boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - @Override - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cf/90781dea644c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cf/90781dea644c0017146ede6da4ae5d42 deleted file mode 100644 index 7be3c94..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/cf/90781dea644c0017146ede6da4ae5d42 +++ /dev/null @@ -1,436 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix.equals(new UnitP(1.0, "ks").UnitPrefix)) - { - System.out.println("Condition 6 true"); - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d/10174905984a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d/10174905984a00171930ee4d171ed0de deleted file mode 100644 index 03251b6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d/10174905984a00171930ee4d171ed0de +++ /dev/null @@ -1,571 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - System.out.println(normalisedInfos.get(0).Value + " " + normalisedInfos.get(0).BaseTenExponent + " " + normalisedInfos.get(0).Prefix.Factor + " -- " + normalisedInfos.get(1).Value + " " + normalisedInfos.get(1).BaseTenExponent + " " + normalisedInfos.get(1).Prefix.Factor); - System.out.println(outInfo.Value + " " + outInfo.BaseTenExponent + " " + outInfo.Prefix.Factor); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d/208cd0476f4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d/208cd0476f4c00171838d4a3813404a0 deleted file mode 100644 index a3ce47c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d/208cd0476f4c00171838d4a3813404a0 +++ /dev/null @@ -1,251 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return null; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || filter == null) return new ArrayList(); - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), filter, defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d/e09af295624c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d/e09af295624c0017146ede6da4ae5d42 deleted file mode 100644 index 75545b7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d/e09af295624c0017146ede6da4ae5d42 +++ /dev/null @@ -1,127 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return - ( - first.Error.equals(second.Error) - ); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type == ErrorTypes.None || secondInfo.Error.Type == ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first.Type == second.Type && - first.Factor == second.Factor - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling == second.ExceptionHandling && - first.Type == second.Type - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Type == second.Type - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/50beab146f4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/50beab146f4c00171838d4a3813404a0 deleted file mode 100644 index 14a4d23..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/50beab146f4c00171838d4a3813404a0 +++ /dev/null @@ -1,254 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return null; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || filter == null) return new ArrayList(); - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), filter, defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/605da14eba4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/605da14eba4a0017160ae291ab4667e2 deleted file mode 100644 index 58198bd..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/605da14eba4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - System.out.println(input); - if (input.toLowerCase() == "y\n") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/c0e2d837964a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/c0e2d837964a00171930ee4d171ed0de deleted file mode 100644 index 8bd7100..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/c0e2d837964a00171930ee4d171ed0de +++ /dev/null @@ -1,574 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - System.out.println(big2.Value); - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - System.out.println(big2.Value); - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/d0b21b02c24a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/d0b21b02c24a00171634abff01ee97d5 deleted file mode 100644 index 2638148..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d0/d0b21b02c24a00171634abff01ee97d5 +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - System.out.println(parseInfo.UnitInfo.Value); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d1/e021d743c34a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d1/e021d743c34a00171634abff01ee97d5 deleted file mode 100644 index 30fe249..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d1/e021d743c34a00171634abff01ee97d5 +++ /dev/null @@ -1,22 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - double test = 0.000000000 - - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits); - - //UnitP test = UnitP.Division - //( - // new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - // new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - //); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d2/80d04c58b34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d2/80d04c58b34a00171059ebc16969059f deleted file mode 100644 index 3b56357..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d2/80d04c58b34a00171059ebc16969059f +++ /dev/null @@ -1,1062 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - UnitInfo test = Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - System.out.println(test.Value); - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d3/306a85dfb84a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d3/306a85dfb84a0017160ae291ab4667e2 deleted file mode 100644 index 1a08858..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d3/306a85dfb84a0017160ae291ab4667e2 +++ /dev/null @@ -1,426 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - String input = System.console().readLine(); - - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - System.console().readLine(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - System.console().readLine(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d3/c06edb3fb94a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d3/c06edb3fb94a0017160ae291ab4667e2 deleted file mode 100644 index 9422003..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d3/c06edb3fb94a0017160ae291ab4667e2 +++ /dev/null @@ -1,431 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.next(); - if (input.toLowerCase() == "y") - { - scanner.close() - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - System.out.println("here"); - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d4/002c9ed32c4c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d4/002c9ed32c4c00171ae7fcf2c321c986 deleted file mode 100644 index 102aa83..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d4/002c9ed32c4c00171ae7fcf2c321c986 +++ /dev/null @@ -1,19 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test0 = new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits); - //System.out.println(test0.ValueAndUnitString); - UnitP test = UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d4/008ac487624c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d4/008ac487624c0017146ede6da4ae5d42 deleted file mode 100644 index 2c537a8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d4/008ac487624c0017146ede6da4ae5d42 +++ /dev/null @@ -1,223 +0,0 @@ -package UnitParser; - -import java.util.AbstractMap; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -public class Prefix implements Comparable -{ - /**Name of the unit prefix.**/ - public final String Name; - /**Symbol of the unit prefix.**/ - public final String Symbol; - /**Multiplying factor associated with the unit prefix.**/ - public final double Factor; - /**Type of the unit prefix.**/ - public final PrefixTypes Type; - /**Usage conditions of the unit prefix.**/ - public final PrefixUsageTypes PrefixUsage; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /**Initialises a new Prefix instance.**/ - public Prefix() - { - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - PrefixUsage = PrefixUsageTypes.DefaultUsage; - } - - /** - Initialises a new Prefix instance. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - } - - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor) - { - this(factor, PrefixUsageTypes.DefaultUsage); - } - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(factor, ""); - - if (Type != PrefixTypes.None) - { - Factor = factor; - Name = GetName(Type, Factor); - - Symbol = Linq.FirstOrDefaultDict - ( - Type == PrefixTypes.SI ? HCPrefixes.AllSIPrefixSymbols : - HCPrefixes.AllBinaryPrefixSymbols, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(null, 0.0) - ) - .getKey(); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol) - { - this(symbol, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(1.0, symbol); - - if (Type != PrefixTypes.None) - { - Symbol = symbol; - Factor = - ( - Type == PrefixTypes.SI ? - HCPrefixes.AllSIPrefixSymbols.get(symbol) : - HCPrefixes.AllBinaryPrefixSymbols.get(symbol) - ); - Name = GetName(Type, Factor); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name prefix Prefix variable whose information will be used. - **/ - public Prefix(Prefix prefix) - { - if (prefix == null) prefix = new Prefix(); - - Name = prefix.Name; - Symbol = prefix.Symbol; - Factor = prefix.Factor; - Type = prefix.Type; - PrefixUsage = prefix.PrefixUsage; - } - - private static PrefixTypes GetType(double factor, String symbol) - { - PrefixTypes outType = PrefixTypes.None; - if (factor == 1.0 && symbol == "") return outType; - - if (factor != 1.0) - { - if (HCPrefixes.AllSIPrefixes.containsValue(factor)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixes.containsValue(factor)) - { - outType = PrefixTypes.Binary; - } - } - else - { - if (HCPrefixes.AllSIPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.Binary; - } - } - - return outType; - } - - private static String GetName(PrefixTypes type, double factor) - { - return - ( - type == PrefixTypes.SI ? - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) : - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - ) - .getKey().toString(); - } - - @Override - ///Compares the current instance against another Prefix one. - ///The other Prefix instance. - public int compareTo(Prefix other) - { - return new Double(this.Factor).compareTo - ( - new Double(other.Factor) - ); - } - - @Override - ///Determines whether the current Prefix instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((Prefix)obj); - } - - boolean Equals(Prefix other) - { - return - ( - other == null ? false : - Equals.PrefixesAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this Prefix instance. - public int hashCode() { return 0; } - -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d6/1090bf829e4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d6/1090bf829e4a00171930ee4d171ed0de deleted file mode 100644 index 2143dbc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d6/1090bf829e4a00171930ee4d171ed0de +++ /dev/null @@ -1,51 +0,0 @@ -package test0; - -import java.util.Comparator; -import java.util.HashMap; - -import InternalUnitParser.CSharpAdaptation.Linq; -import InternalUnitParser.Hardcoding.HCPrefixes; -import UnitParser.UnitP; -import UnitParser.UnitSymbols; - -public class Main -{ - public static void main(String[] args) throws Exception - { - HashMap test0 = new HashMap(); - test0.put("Three", 3.0); - test0.put("One", 1.0); - test0.put("Four", 4.0); - test0.put("Two", 2.0); - test0.put("Five", 5.0); - - HCPrefixes.BigSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - test0, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - - for(Double item: HCPrefixes.BigSIPrefixValues) - { - System.out.println(item); - } - - - //UnitP test = UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")); - //UnitP.Addition(UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ")); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d8/301f953b1c4900171bf99b86feeed734 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d8/301f953b1c4900171bf99b86feeed734 deleted file mode 100644 index 64e09d2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d8/301f953b1c4900171bf99b86feeed734 +++ /dev/null @@ -1,316 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - X output = null; - try - { - output = GetFirst - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return output; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal, ExceptionTypes type) throws Exception - { - if (input == null) - { - return GetDefaultOrException(defaultVal, type); - } - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return GetDefaultOrException(defaultVal, type); - } - - private static X GetDefaultOrException(X defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - public static Map.Entry FirstDict(HashMap input) throws Exception - { - return FirstDict(input, null); - } - - public static Map.Entry FirstDict(HashMap input, Predicate> filter) throws Exception - { - if (filter != null) input = WhereDict(input, filter); - - return GetFirstDict - ( - input, filter, null, ExceptionTypes.FirstDict - ); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - HashMap input2 = new HashMap - ( - filter == null ? input : WhereDict(input, filter) - ); - - Map.Entry output = null; - - try - { - output = GetFirstDict - ( - input2, filter, defaultVal, ExceptionTypes.None - ); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying with the Java compiler requirements. - } - - return output; - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal, ExceptionTypes type - ) - throws Exception - { - if (input == null) - { - return GetDefaultOrExceptionDict(defaultVal, type); - } - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return GetDefaultOrExceptionDict(defaultVal, type); - } - - private static Map.Entry GetDefaultOrExceptionDict(Map.Entry defaultVal, ExceptionTypes type) throws Exception - { - if (type != ExceptionTypes.None) - { - ThrowException(type); - } - - return defaultVal; - } - - private static void ThrowException(ExceptionTypes type) throws Exception - { - String method = "First"; - if (type == ExceptionTypes.FirstDict) - { - method = " (1-D collections)"; - } - else if (type == ExceptionTypes.First) - { - method = " (dictionaries)"; - } - - throw new Exception("Exception provoked by an error in the custom version of the " + method + " LINQ method."); - } - - enum ExceptionTypes { None, First, FirstDict } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d8/b0d6e55eb04a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d8/b0d6e55eb04a00171059ebc16969059f deleted file mode 100644 index d3986bc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d8/b0d6e55eb04a00171059ebc16969059f +++ /dev/null @@ -1,1054 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - System.out.println(tempInfo.Value + " " + tempInfo.BaseTenExponent); - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/3007d771ab4a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/3007d771ab4a00171059ebc16969059f deleted file mode 100644 index 71fffec..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/3007d771ab4a00171059ebc16969059f +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - System.out.println(targetPart.Unit + " " + targetPart.Prefix.Factor); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/30478da57a4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/30478da57a4c00171945f16efe0d9b5d deleted file mode 100644 index 381f685..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/30478da57a4c00171945f16efe0d9b5d +++ /dev/null @@ -1,1052 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = (int)Math.signum(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - tempInfo = Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/60f6749f934a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/60f6749f934a00171930ee4d171ed0de deleted file mode 100644 index fc7a4a4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/60f6749f934a00171930ee4d171ed0de +++ /dev/null @@ -1,566 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/c06c6abf5a4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/c06c6abf5a4c0017146ede6da4ae5d42 deleted file mode 100644 index 9057735..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/c06c6abf5a4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1183 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - ( - this.Value * this.UnitPrefix.Factor - ) - .compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/c09844a2624c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/c09844a2624c0017146ede6da4ae5d42 deleted file mode 100644 index 99bd69c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/d9/c09844a2624c0017146ede6da4ae5d42 +++ /dev/null @@ -1,126 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; - -import java.util.ArrayList; - -public class Equals -{ - public static boolean UnitPVarsAreEqual(UnitP first, UnitP second) - { - return - ( - UnitPNonUnitInfoAreEqual(first, second) && - UnitPUnitInfoAreEqual(first, second) - ); - } - - static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second) - { - return - ( - first.Error.equals(second.Error) - ); - } - - static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second) - { - return UnitInfosAreEqual - ( - ExceptionInstantiation.NewUnitInfo(first.Value, first.Unit, first.UnitPrefix), - ExceptionInstantiation.NewUnitInfo(second.Value, second.Unit, second.UnitPrefix) - ); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return UnitInfosAreEqual(firstInfo, secondInfo, false); - } - - public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues) - { - if (firstInfo.Error.Type == ErrorTypes.None || secondInfo.Error.Type == ErrorTypes.None) - { - return firstInfo.Error.Type == secondInfo.Error.Type; - } - - UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo); - UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo); - - return - ( - (ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) && - UnitInfoUnitsAreEqual(firstInfo2, secondInfo2) - ); - } - - //This method assumes that both inputs are normalised. - static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo) - { - return - ( - firstInfo.BaseTenExponent == secondInfo.BaseTenExponent && - firstInfo.Value == secondInfo.Value - ); - } - - public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit) - { - return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts); - } - - //This method expects fully expanded/simplified unit parts. - static boolean UnitPartListsAreEqual(ArrayList firstParts, ArrayList secondParts) - { - if (firstParts.size() != secondParts.size()) return false; - - for (UnitPart firstPart: firstParts) - { - if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null) - { - return false; - } - } - - return true; - } - - public static boolean PrefixesAreEqual(Prefix first, Prefix second) - { - return - ( - first.Type == second.Type && - first.Factor == second.Factor - ); - } - - public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Unit == second.Unit && - first.Prefix.Factor == second.Prefix.Factor - ); - } - - public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second) - { - return - ( - first.ExceptionHandling == second.ExceptionHandling && - first.Type == second.Type - ); - } - - public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second) - { - return - ( - first.Exponent == second.Exponent && - first.Type == second.Type - ); - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/da/c01715a9614c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/da/c01715a9614c0017146ede6da4ae5d42 deleted file mode 100644 index 6b69ea0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/da/c01715a9614c0017146ede6da4ae5d42 +++ /dev/null @@ -1,29 +0,0 @@ -package test0; - -import java.util.ArrayList; -import java.util.Collections; - -import UnitParser.*; - -public class Main -{ - public static void main(String[] args) throws Exception - { - ArrayList tests = new ArrayList(); - tests.add(new Prefix(2555.0)); - tests.add(new Prefix(1000.0)); - tests.add(new Prefix(500000)); - - if(tests.get(0).equals(tests.get(2))) - { - System.out.println("Is OK"); - } - - Collections.sort(tests); - - for (Prefix item: tests) - { - System.out.println(item.Factor); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/db/5073faedb14a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/db/5073faedb14a00171059ebc16969059f deleted file mode 100644 index 204827c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/db/5073faedb14a00171059ebc16969059f +++ /dev/null @@ -1,1059 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - UnitInfo test22 = Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - System.out.println(original2.Value); - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/db/a06ffedea74a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/db/a06ffedea74a00171059ebc16969059f deleted file mode 100644 index 86363b9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/db/a06ffedea74a00171059ebc16969059f +++ /dev/null @@ -1,13 +0,0 @@ -package test0; - -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP("1 ft"); //UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft")); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/db/c02918949a4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/db/c02918949a4a00171930ee4d171ed0de deleted file mode 100644 index bbb262a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/db/c02918949a4a00171930ee4d171ed0de +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/dd/30ef1c936e4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/dd/30ef1c936e4c00171838d4a3813404a0 deleted file mode 100644 index 315291d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/dd/30ef1c936e4c00171838d4a3813404a0 +++ /dev/null @@ -1,254 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - return (ArrayList) input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) - { - return input; - } - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - ArrayList input2 = new ArrayList - ( - filter == null ? input : Where(input, filter) - ); - - if (input == null) return defaultVal; - - ArrayList tempVar = - ( - filter == null ? input : - Where(input, filter) - ); - if (tempVar == null) return defaultVal; - - return GetFirst(input2, filter, defaultVal); ; - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - private static X GetFirst(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : (Iterable)input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), filter, defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - private static Map.Entry GetFirstDict - ( - HashMap input, Predicate> filter, Map.Entry defaultVal - ) - { - if (input == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/de/10d02e33b14b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/de/10d02e33b14b00171c69d98bf667dda6 deleted file mode 100644 index e7ee622..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/de/10d02e33b14b00171c69d98bf667dda6 +++ /dev/null @@ -1,19 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test0 = new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits); - System.out.println(test0.ValueAndUnitString); - UnitP test = UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/de/20391c4f6f4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/de/20391c4f6f4c00171838d4a3813404a0 deleted file mode 100644 index 0eec979..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/de/20391c4f6f4c00171838d4a3813404a0 +++ /dev/null @@ -1,251 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return null; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || filter == null) return new ArrayList(); - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), filter, defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/de/90c65ddae54c00171118892245944c7f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/de/90c65ddae54c00171118892245944c7f deleted file mode 100644 index b350d58..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/de/90c65ddae54c00171118892245944c7f +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/df/20975e359a4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/df/20975e359a4a00171930ee4d171ed0de deleted file mode 100644 index 5311d6e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/df/20975e359a4a00171930ee4d171ed0de +++ /dev/null @@ -1,1032 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -public class MethodsUnitP -{ - public static ParseInfo ParseInputs(ParseInfo parseInfo) - { - parseInfo = Parse.StartUnitParse(parseInfo); - boolean isOK = - ( - parseInfo.UnitInfo.Error.Type == ErrorTypes.None && - parseInfo.UnitInfo.Unit != Units.None - ); - - if (!isOK && parseInfo.InputToParse.contains(" ")) - { - //No intermediate spaces (within the unit) should be expected, - //but well... - ParseInfo parseInfo2 = new ParseInfo - ( - parseInfo, CSharpOther.StringJoin - ( - "", Linq.Select - ( - CSharpOther.ArrayToArrayList - ( - CSharpOther.SplitTryCatch(parseInfo.InputToParse, " ") - ), - x -> x.trim() - ) - ) - ); - parseInfo2.UnitInfo.Error = new ErrorInfo(); - parseInfo2 = Parse.StartUnitParse(parseInfo2); - - if (parseInfo2.UnitInfo.Unit != Units.None) - { - parseInfo = new ParseInfo(parseInfo2); - } - } - - return parseInfo; - } - - public static UnitInfo ParseValueAndUnit(String valueAndUnit) - { - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(); - String[] parts = CSharpOther.SplitTryCatch - ( - valueAndUnit.trim(), " " - ); - - //Note that Parse.ParseDecimal can deal with any number (i.e., double, double or beyond double). - if (parts.length >= 2) - { - unitInfo = Parse.ParseDecimal(parts[0]); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = CSharpOther.StringJoin(" ", parts, 1, parts.length - 1); - } - } - else if (parts.length == 1) - { - unitInfo = Parse.ParseDecimal(valueAndUnit); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = "Unitless"; - } - } - - return - ( - unitInfo.Error.Type == ErrorTypes.None ? unitInfo : - ParseValueAndUnitNoBlank(valueAndUnit) - ); - } - - public static UnitInfo ParseValueAndUnitNoBlank(String valueAndUnit) - { - String valueString = CSharpOther.StringJoinChars - ( - "", Linq.TakeWhile - ( - CSharpOther.StringToCharacters(valueAndUnit.trim().toLowerCase()), - x -> Character.isDigit(x) || x.equals('e') || x.equals('-') || - x.equals('+') || x.equals('.') || x.equals(','), '\u0000' - ) - ); - - UnitInfo unitInfo = Parse.ParseDecimal(valueString); - - if (unitInfo.Error.Type == ErrorTypes.None) - { - unitInfo.TempString = valueAndUnit.replace(valueString, ""); - } - - return unitInfo; - } - - public UnitPConstructor GetUnitP2(double value, String unitString) - { - return GetUnitP2 - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException - ); - } - - public UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - return GetUnitP2 - ( - value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage - ); - } - - public static UnitPConstructor GetUnitP2 - ( - double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - return GetUnitP2 - ( - ExceptionInstantiation.NewUnitInfo(value, exceptionHandling, prefixUsage), unitString - ); - } - - public static UnitPConstructor GetUnitP2(UnitInfo unitInfo, String unitString) - { - ParseInfo parseInfo = - ( - unitInfo.Error.Type != ErrorTypes.None ? - new ParseInfo(unitInfo) : ParseInputs - ( - new ParseInfo(unitInfo, unitString) - ) - ); - - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None && parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return new UnitPConstructor - ( - unitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, - parseInfo.UnitInfo.System, parseInfo.UnitInfo.Error.Type, - unitInfo.Error.ExceptionHandling, false, - (unitInfo.Value != parseInfo.UnitInfo.Value) - ); - } - - public static UnitInfo ImproveUnitInfo(UnitInfo unitInfo, boolean noPrefixImprovement) - { - if (unitInfo.Parts.size() == 0) - { - if (unitInfo.Prefix.Factor != 1.0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - } - - unitInfo.Unit = Units.Unitless; - unitInfo.Prefix = new Prefix(1.0, unitInfo.Prefix.PrefixUsage); - } - else if (Math.abs(unitInfo.Value) < 1 && unitInfo.Prefix.Factor > 1) - { - unitInfo.Value = unitInfo.Value * unitInfo.Prefix.Factor; - unitInfo.Prefix = new Prefix(unitInfo.Prefix.PrefixUsage); - } - - unitInfo = RemoveUnitPartPrefixes(unitInfo); - - if (!noPrefixImprovement) - { - unitInfo = ImprovePrefixes(unitInfo); - } - - return ReduceBigValueExp(unitInfo); - } - - static UnitInfo RemoveUnitPartPrefixes(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 2 || !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - //The only cases with (uncompensated) prefixes in some unit parts which - //might reach this point are multi-part unnamed compounds. - return unitInfo; - } - - UnitInfo prefixInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 0; i < unitInfo.Parts.size(); i++) - { - if (unitInfo.Parts.get(i).Prefix.Factor == 1.0) continue; - - if (isBasicPrefixUnit(unitInfo.Parts.get(i))) - { - //Better keeping the prefixes of the basic units (e.g., kg). - continue; - } - - prefixInfo = Managed.PerformManagedOperationUnits - ( - prefixInfo, Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, unitInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - unitInfo.Parts.get(i).Prefix = new Prefix(); - } - - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, prefixInfo, Operations.Multiplication - ); - - return unitInfo; - } - - static boolean isBasicPrefixUnit(UnitPart unitPart) - { - for (HashMap item: HCCompounds.AllBasicUnits.values()) - { - for (BasicUnit item2: item.values()) - { - if (item2.Unit == unitPart.Unit && item2.PrefixFactor == unitPart.Prefix.Factor) - { - return true; - } - } - } - - return false; - } - - static UnitInfo ReduceBigValueExp(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - double maxVal = 1000000.0; - double minVal = 0.0001; - - int sign = (int)Math.signum(unitInfo.Value); - double absValue = Math.abs(unitInfo.Value); - - if (unitInfo.BaseTenExponent > 0) - { - while (unitInfo.BaseTenExponent > 0 && absValue <= maxVal / 10) - { - unitInfo.BaseTenExponent -= 1; - absValue *= 10; - } - } - else - { - while (unitInfo.BaseTenExponent < 0 && absValue >= minVal * 10) - { - unitInfo.BaseTenExponent += 1; - absValue /= 10; - } - } - - unitInfo.Value = sign * absValue; - - return unitInfo; - } - - static UnitInfo ImprovePrefixes(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless) - { - return Managed.NormaliseUnitInfo(unitInfo); - } - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - double absValue = Math.abs(unitInfo.Value); - boolean valueIsOK = (absValue >= 0.001 && absValue <= 1000.0); - - if (valueIsOK && unitInfo.BaseTenExponent == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - - PrefixTypes prefixType = - ( - unitInfo.Prefix.Type != PrefixTypes.None ? - unitInfo.Prefix.Type : PrefixTypes.SI - ); - - boolean prefixIsOK = PrefixCanBeUsedWithUnit(unitInfo, prefixType); - - if (!prefixIsOK || !valueIsOK || unitInfo.BaseTenExponent != 0) - { - unitInfo = Managed.NormaliseUnitInfo(unitInfo); - - if (prefixIsOK) - { - unitInfo = MethodsCommon.GetBestPrefixForTarget - ( - unitInfo, unitInfo.BaseTenExponent, - prefixType, true - ); - } - } - - return CompensateBaseTenExponentWithPrefix(unitInfo); - } - - static boolean PrefixCanBeUsedWithUnit(UnitInfo unitInfo, PrefixTypes prefixType) - { - return - ( - !PrefixCanBeUsedWithUnitBasicCheck(unitInfo, prefixType) ? false : - PrefixCanBeUsedCompound(unitInfo) - ); - } - - //It is better to not use prefixes with some compounds in order to avoid misinterpretations. - //For example: 1000 m2 converted into k(m2) is easily misinterpretable as km2 (i.e., (km)^2). - static boolean PrefixCanBeUsedCompound(UnitInfo unitInfo) - { - boolean canBeUsed = true; - - if (MethodsCommon.UnitIsNamedCompound(unitInfo.Unit)) - { - canBeUsed = HCPrefixes.AllCompoundsUsingPrefixes.contains(unitInfo.Unit); - } - else if (unitInfo.Parts.size() > 1) canBeUsed = false; - - return canBeUsed; - } - - static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - MethodsCommon.GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - MethodsCommon.GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo CompensateBaseTenExponentWithPrefix(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0 || unitInfo.Prefix.Factor == 1) return unitInfo; - - UnitInfo tempInfo = Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitInfo, 1.0) - ); - - tempInfo = MethodsCommon.GetBestPrefixForTarget - ( - tempInfo, tempInfo.BaseTenExponent, - unitInfo.Prefix.Type, true - ); - - unitInfo = ExceptionInstantiation.NewUnitInfo - ( - unitInfo, unitInfo.Value, tempInfo.BaseTenExponent, new Prefix(tempInfo.Prefix) - ); - - return Managed.PerformManagedOperationValues - ( - unitInfo, tempInfo = ExceptionInstantiation.NewUnitInfo - ( - tempInfo, 0, new Prefix() - ), - Operations.Multiplication - ); - } - - enum RoundType { MidpointAwayFromZero, MidpointToZero }; - - //The current implementation only needs the double type and that's why all this part - //of the algorithm is declared as double. - //Nevertheless, the original version of this code (i.e., an improved version of the one - //I submitted for the CoreFX issue https://github.com/dotnet/corefx/issues/6308) was built - //on dynamic. Thus, the current structure can be easily adapted to deal with as many types - //as required. - static double[] Power10Decimal = PopulateRoundPower10Array(); - - static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This function (+ all the related code) is a version of NumberParser's Math2.RoundExact - //(https://github.com/varocarbas/FlexibleParser/blob/master/all_code/NumberParser/Source/Math2/Private/New/Math2_Private_New_RoundTruncate.cs). - //Note that Math.Round cannot deal with the rounding-down expectations of ImproveFinalValue. - static double RoundExact(double d, int digits, RoundType type) - { - return - ( - d == 0.0 ? 0.0 : (d > 0.0 ? 1.0 : -1.0) * - RoundInternalAfter(Math.abs(d), digits, type) - ); - } - - static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Power10Decimal[zeroCount]; - d3 = DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = GetIntegerLength(d3); - - double headingBit = 0.0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2.0; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Power10Decimal[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Power10Decimal[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Power10Decimal[zeroCount] - ); - } - - //This method expects the input value to always be positive. - static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Decimal.length - 1; i++) - { - if (d < Power10Decimal[i + 1]) return i + 1; - } - - return Power10Decimal.length; - } - - static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = DecimalPartToInteger(d2, digits); - int length2 = GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal(d2, length2 - digits, type) - / Power10Decimal[length2] - ) - ); - } - - static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Power10Decimal[remDigits]) - ); - - double rounded2 = rounded * Power10Decimal[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1.0) rounded += 1.0; - else if (greaterEqual == 0.0) - { - if (type == RoundType.MidpointAwayFromZero) - { - rounded += 1.0; - } - } - - return rounded; - } - - static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Power10Decimal[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Power10Decimal[Power10Decimal.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Power10Decimal[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Power10Decimal[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Power10Decimal[remDigits - 1]); - return - ( - d - rounded * Math.floor(Power10Decimal[remDigits]) == middle ? 0 : 1 - ); - } - - static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - static double DecimalPartToInteger(double d2, int digits, Boolean untilEnd) - { - if (digits + 1 >= Power10Decimal.length - 1) - { - d2 *= Power10Decimal[Power10Decimal.length - 1]; - } - else - { - d2 *= Power10Decimal[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - while (d2 < Power10Decimal[Power10Decimal.length - 3] && (untilEnd || (lastDigit > 0 && lastDigit <= 5.0))) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Decimal[0] % 10); - } - } - - return d2; - } - - //This method depends upon the double-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001m - //outputting zero because of being automatically converted into 100000000000000000m. - //This method expects the input value to always be positive. - static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while (d2 <= OperationsOther.MaxValue / 10.0) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Decimal[0] % 10.0) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - - //This method improves values which have likely been affected by the precision of the calculations. - //For example: 1.2999999999999 actually being 1.3. - public static double ImproveFinalValue(double value) - { - if (value == 0.0) return value; - double sign = value / Math.abs(value); - double absValue = Math.abs(value); - int minGapDigits = 6; - - UnitInfo infoUp = GetTargetRoundedValue(absValue, RoundType.MidpointAwayFromZero); - if (infoUp.Value > absValue && infoUp.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23459999999999999999 into 0.2346. - value = sign * infoUp.Value; - } - else - { - UnitInfo infoDown = GetTargetRoundedValue(absValue, RoundType.MidpointToZero); - if (infoDown.Value < absValue && infoDown.BaseTenExponent >= minGapDigits) - { - //Performs improvements like converting 0.23450000000000004 into 0.2345. - value = sign * infoDown.Value; - } - } - - return value; - } - - static UnitInfo GetTargetRoundedValue(double value, RoundType roundType) - { - //UnitInfo has a perfect format to store the returned two values (double & integer). - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - RoundExact(value, 1, roundType) - ); - - //Loop iterating through all the digits (up to the maximum double precision) and looking - //for situations with many consecutive irrelevant (i.e., no effect on rounding) digits. - Boolean started = false; - int startCount = 0; - int startTarget = 4; - for (int i = 2; i < 27; i++) - { - double tempVal = RoundExact(value, i, roundType); - - if (!started) - { - if (tempVal == outInfo.Value) - { - startCount += 1; - if (startCount == startTarget) started = true; - } - else - { - //Starting the analysis of consecutive irrelevant digits right away might be counter-producing. - //Once the process is started, any exception (i.e., a non-irrelevant digit) would provoke the - //analysis to immediately fail. That's why better delaying the analysis start until seeing some - //consecutive digits (i.e., higher chances of finding what is expected). - startCount = 0; - } - } - else if (started) - { - if (tempVal != outInfo.Value) return outInfo; - outInfo.BaseTenExponent += 1; - } - - outInfo.Value = tempVal; - } - - return outInfo; - } - - public static ArrayList GetUnitsTypeCommon(UnitTypes type) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) - ) - ), - x -> x.getKey() - ) - ); - } - - public static ArrayList GetUnitsTypeAndSystemCommon(UnitTypes type, UnitSystems system) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - Linq.SelectDict - ( - Linq.WhereDict - ( - HCMain.AllUnitConversionFactors, - ( - x -> MethodsCommon.GetTypeFromUnit(x.getKey()).equals(type) && - UnitBelongsToSystem(x.getKey(), system) - ) - ), - x -> x.getKey() - ) - ); - } - - static boolean UnitBelongsToSystem(Units unit, UnitSystems targetSystem) - { - UnitSystems system = MethodsCommon.GetSystemFromUnit(unit); - - return - ( - system == targetSystem ? true : - ( - HCMain.AllMetricEnglish.get(targetSystem) == UnitSystems.Imperial && - HCMain.AllMetricEnglish.get(system) == UnitSystems.Imperial && - HCUnits.AllImperialAndUSCSUnits.contains(unit) - ) - ); - } - - public static ArrayList GetStringsUnitCommon(Units unit, boolean otherStringsToo) - { - return - ( - unit == Units.None || unit == Units.Unitless || MethodsCommon.IsUnnamedUnit(unit) ? - new ArrayList() : Linq.Distinct - ( - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Unit, unit - ) - ) - ) - ); - } - - public static ArrayList GetStringsTypeCommon(UnitTypes type, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None ? new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), InputTypes.Type, Units.None, type - ) - ) - ); - } - - public static ArrayList GetStringsTypeAndSystemCommon(UnitTypes type, UnitSystems system, boolean otherStringsToo) - { - return - ( - type == UnitTypes.None || system == UnitSystems.None ? - new ArrayList() : - GetUnitStringsCommon - ( - GetAllStringsSpecific - ( - GetAllStrings(otherStringsToo), - InputTypes.TypeAndSystem, - Units.None, type, system - ) - ) - ); - } - - static ArrayList> GetAllStrings(boolean otherStringsToo) - { - //Symbols (case matters). - ArrayList> allStrings = Linq.SelectDict - ( - HCUnits.AllUnitSymbols, x -> x - ); - - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitSymbols2, x -> x) - ); - - if (otherStringsToo) - { - //Further Strings (case doesn't matter). - allStrings.addAll - ( - Linq.SelectDict(HCMain.AllUnitStrings, x -> x) - ); - } - - return Linq.OrderBy - ( - allStrings, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, Units.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, UnitTypes.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, Units unit, UnitTypes type - ) - { - return GetAllStringsSpecific - ( - allSymbols, inputType, unit, type, UnitSystems.None - ); - } - - static ArrayList> GetAllStringsSpecific - ( - ArrayList> allSymbols, InputTypes inputType, - Units unit, UnitTypes type, UnitSystems system - ) - { - if (inputType == InputTypes.Unit) - { - return Linq.Where - ( - allSymbols, x -> x.getValue().equals(unit) - ); - } - else if (inputType == InputTypes.Type) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) - ); - } - else if (inputType == InputTypes.TypeAndSystem) - { - return Linq.Where - ( - allSymbols, x -> MethodsCommon.GetTypeFromUnit(x.getValue()).equals(type) && - UnitBelongsToSystem(x.getValue(), system) - ); - } - - return allSymbols; - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings) - { - return GetUnitStringsCommon(allStrings, ""); - } - - static ArrayList GetUnitStringsCommon(ArrayList> allStrings, String prefixAbbrev) - { - ArrayList outList = new ArrayList(); - - for (Entry item: allStrings) - { - String item2 = item.getKey(); - - if (prefixAbbrev != "" && !HCMain.AllUnitStrings.containsKey(item.getKey())) - { - item2 = prefixAbbrev + item2; - } - - outList.add(item2); - } - - return outList; - } - - public static UnitP ConvertToCommon(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - Prefix prefix = - ( - targetPrefix != null ? new Prefix(targetPrefix) : - new Prefix(1.0, unitP.UnitPrefix.PrefixUsage) - ); - - return ConvertToCommon - ( - //Calling UpdateMainUnitVariables is required to populate the type/system variables. - unitP, Parse.UpdateMainUnitVariables - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, targetUnit, prefix, true, unitP.Error.ExceptionHandling - ) - ) - ); - } - - public static UnitP ConvertToCommon(UnitP original, String unitString) - { - ParseInfo parseInfo = Parse.StartUnitParse - ( - new ParseInfo - ( - ExceptionInstantiation.NewUnitInfo - ( - original, 0.0, 0, new Prefix(original.UnitPrefix.PrefixUsage) - ), - unitString - ) - ); - - return ConvertToCommon(original, parseInfo.UnitInfo); - } - - public static UnitP ConvertToCommon(UnitP original, UnitInfo targetInfo) - { - ErrorTypes error = MethodsCommon.PrelimaryErrorCheckConversion(original, targetInfo); - if (error != ErrorTypes.None) - { - return new UnitP(original, error); - } - - UnitInfo originalInfo = ExceptionInstantiation.NewUnitInfo(original); - UnitInfo infoResult = Conversions.ConvertUnit(originalInfo, targetInfo, false); - - return - ( - infoResult.Error.Type != ErrorTypes.None ? - new UnitP(original, infoResult.Error.Type) : - new UnitP - ( - infoResult, original, - original.OriginalUnitString + " => " + - MethodsCommon.GetUnitString(infoResult) - ) - ); - } - - - enum InputTypes { Unit, Type, TypeAndSystem, System } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/df/b00ade3eb34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/df/b00ade3eb34a00171059ebc16969059f deleted file mode 100644 index 3393b0d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/df/b00ade3eb34a00171059ebc16969059f +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - System.out.println(outInfo.Value); - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/df/d09ac06af74c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/df/d09ac06af74c00171048b3f61ecb42d3 deleted file mode 100644 index 8a2fe3d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/df/d09ac06af74c00171048b3f61ecb42d3 +++ /dev/null @@ -1,97 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.Operations.*; - -/**Contains the main information associated with the constituent parts of each unit.**/ -public class UnitPart -{ - /**Unit associated with the current part.**/ - public Units Unit; - /**Prefix information associated with the current part.**/ - public Prefix Prefix; - /**Exponent associated with the current part.**/ - public Integer Exponent; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /**Initialises a new UnitPart instance. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exponent Integer exponent to be used. - **/ - public UnitPart(Units unit, Prefix prefix) - { - this(unit, prefix, 1); - } - - /**Initialises a new UnitPart instance. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exponent Integer exponent to be used. - **/ - public UnitPart(Units unit, Prefix prefix, int exponent) - { - Unit = unit; - Prefix = new Prefix(prefix); - Exponent = exponent; - } - - /** - Initialises a new UnitPart instance. - @param unit Member of the Units enum to be used. - @param exponent Integer exponent to be used. - **/ - public UnitPart(Units unit) - { - this(unit, 1); - } - - /** - Initialises a new UnitPart instance. - @param unit Member of the Units enum to be used. - @param exponent Integer exponent to be used. - **/ - public UnitPart(Units unit, int exponent) - { - Unit = unit; - Prefix = new Prefix(1.0); - Exponent = exponent; - } - - /** - Initialises a new UnitPart instance. - @param unitPart UnitPart variable whose information will be used. - **/ - public UnitPart(UnitPart unitPart) - { - if (unitPart == null) unitPart = new UnitPart(Units.None); - - Unit = unitPart.Unit; - Prefix = new Prefix(unitPart.Prefix); - Exponent = unitPart.Exponent; - } - - /** - Determines whether the current UnitPart instance is equal to other one - @param obj Other variable. - **/ - @Override - public boolean equals(Object obj) - { - return Equals((UnitPart)obj); - } - - boolean Equals(UnitPart other) - { - return - ( - other == null ? false : - Equals.UnitPartsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitPart instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e/2083cd48954a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e/2083cd48954a00171930ee4d171ed0de deleted file mode 100644 index 69c4391..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e/2083cd48954a00171930ee4d171ed0de +++ /dev/null @@ -1,575 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - //unitInfos2.get(bigSmallI[0]).Value = big2.Value; - //unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e/30ab5bbeb24b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e/30ab5bbeb24b00171c69d98bf667dda6 deleted file mode 100644 index 22b502b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e/30ab5bbeb24b00171c69d98bf667dda6 +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/305e7e1fb94a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/305e7e1fb94a0017160ae291ab4667e2 deleted file mode 100644 index 2850b1c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/305e7e1fb94a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.next(); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - System.out.println("here"); - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/30629f88794c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/30629f88794c00171945f16efe0d9b5d deleted file mode 100644 index 9b65c79..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/30629f88794c00171945f16efe0d9b5d +++ /dev/null @@ -1,81 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if (input != null && (input.contains("e") || !(val.isNaN() || val.isInfinite()))) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input) throws Exception - { - if - ( - input == null || Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(input.toLowerCase()), x -> !Character.isDigit(x) && - x != '.' && x != ',' && x != '-' && x != '+', '\u0000' - ) - != '\u0000' - ) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - throw new Exception(); - } - - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/40c4b9272b4c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/40c4b9272b4c00171ae7fcf2c321c986 deleted file mode 100644 index 1fc1ff3..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/40c4b9272b4c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - System.out.println(exponent); - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/80f54507b94a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/80f54507b94a0017160ae291ab4667e2 deleted file mode 100644 index 9c41b37..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e0/80f54507b94a0017160ae291ab4667e2 +++ /dev/null @@ -1,429 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.next(); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e1/3078c48f284c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e1/3078c48f284c00171ae7fcf2c321c986 deleted file mode 100644 index fd59426..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e1/3078c48f284c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - System.out.println(outInfo.Value + " " + outInfo.BaseTenExponent); - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e1/a028512ebb4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e1/a028512ebb4a0017160ae291ab4667e2 deleted file mode 100644 index 07c809e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e1/a028512ebb4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e2/90305b997e4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e2/90305b997e4c00171945f16efe0d9b5d deleted file mode 100644 index 9b00973..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e2/90305b997e4c00171945f16efe0d9b5d +++ /dev/null @@ -1,101 +0,0 @@ -package InternalUnitParser.Operations; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class OperationsOther -{ - public static String GetOperationString(UnitP first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(UnitP first, Double second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), second.toString(), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(Double first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - first.toString(), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - private static String GetUnitPString(UnitP unitP) - { - return unitP.OriginalUnitString; - } - - private static String ConcatenateOperationString(String first, String second, char operation) - { - return (first + " " + operation + " " + second); - } - - //NOTE: the order within each char[] collection does matter. The first element will be treated as the default - //symbol for the given operation (e.g., used when creating a String including that operation). - public static HashMap> OperationSymbols; - - public static ArrayList UnitParseIgnored; - - public static final double MaxValue = 79228162514264337593543950335.0; //C# Decimal.MaxValue actual value. - public static final double MinValue = 0.0000000000000000000000000001; //C# Decimal precision lowest limit. - - public static String Start() - { - OperationSymbols = new HashMap>() - { - { - { - put - ( - Operations.Addition, new ArrayList() - {{ - add('+'); - }} - ); - put - ( - Operations.Subtraction, new ArrayList() - {{ - add('-'); add('−'); add('—'); - }} - ); - put - ( - Operations.Multiplication, new ArrayList() - {{ - add('*'); add('x'); add('X'); add('×'); add('⊗'); add('â‹…'); add('·'); - }} - ); - put - ( - Operations.Division, new ArrayList() - {{ - add('/'); add('∕'); add('â„'); add('÷'); add('|'); add('\\'); - }} - ); - } - } - }; - - UnitParseIgnored = new ArrayList() - {{ - add("."); add(","); add(":"); add(";"); add("_"); add("^"); add("+"); - add("#"); add("("); add(")"); add("["); add("]"); add("{"); add("}"); - add("="); add("!"); add("?"); add("@"); add("&"); - }}; - - return ""; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e4/3052e0896f4c00171838d4a3813404a0 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e4/3052e0896f4c00171838d4a3813404a0 deleted file mode 100644 index 7354b95..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e4/3052e0896f4c00171838d4a3813404a0 +++ /dev/null @@ -1,254 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/**Class including Java custom versions for all the System.Linq methods used in the original C# code.**/ -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return null; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || input.entrySet() == null || filter == null) - { - return new ArrayList(); - } - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.entrySet() == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefault - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e5/70baa72a414c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e5/70baa72a414c00171eb8e3cba3fc21fa deleted file mode 100644 index baffd85..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e5/70baa72a414c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,84 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - System.out.println(input + " " + output.IsOK); - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //Emulating the conditions of the original C# version where decimal numbers cannot be parsed as integer. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input) throws Exception - { - if - ( - input == null || Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(input.toLowerCase()), - x -> !Character.isDigit(x) && x != '.' && x != ',' && x != 'e', '\u0000' - ) - != '\u0000' - ) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - //Note that TryParseOutput analyses the exponential cases (i.e., including e + integer exponent) further. - throw new Exception(); - } - - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e6/40e87fc7f04c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e6/40e87fc7f04c00171048b3f61ecb42d3 deleted file mode 100644 index 30e3fae..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e6/40e87fc7f04c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1209 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e6/a0495ec2604c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e6/a0495ec2604c0017146ede6da4ae5d42 deleted file mode 100644 index ab3764f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e6/a0495ec2604c0017146ede6da4ae5d42 +++ /dev/null @@ -1,221 +0,0 @@ -package UnitParser; - -import java.util.AbstractMap; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; - -public class Prefix implements Comparable -{ - /**Name of the unit prefix.**/ - public final String Name; - /**Symbol of the unit prefix.**/ - public final String Symbol; - /**Multiplying factor associated with the unit prefix.**/ - public final double Factor; - /**Type of the unit prefix.**/ - public final PrefixTypes Type; - /**Usage conditions of the unit prefix.**/ - public final PrefixUsageTypes PrefixUsage; - - /**Initialises a new Prefix instance.**/ - public Prefix() - { - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - PrefixUsage = PrefixUsageTypes.DefaultUsage; - } - - /** - Initialises a new Prefix instance. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Name = "None"; - Symbol = ""; - Factor = 1.0; - Type = PrefixTypes.None; - } - - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor) - { - this(factor, PrefixUsageTypes.DefaultUsage); - } - /** - Initialises a new Prefix instance. - @param name factor Multiplying factor to be used. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(double factor, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(factor, ""); - - if (Type != PrefixTypes.None) - { - Factor = factor; - Name = GetName(Type, Factor); - - Symbol = Linq.FirstOrDefaultDict - ( - Type == PrefixTypes.SI ? HCPrefixes.AllSIPrefixSymbols : - HCPrefixes.AllBinaryPrefixSymbols, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(null, 0.0) - ) - .getKey(); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol) - { - this(symbol, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new Prefix instance. - @param name symbol Symbol (case does matter) defining the current prefix. - @param name prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public Prefix(String symbol, PrefixUsageTypes prefixUsage) - { - PrefixUsage = prefixUsage; - Type = GetType(1.0, symbol); - - if (Type != PrefixTypes.None) - { - Symbol = symbol; - Factor = - ( - Type == PrefixTypes.SI ? - HCPrefixes.AllSIPrefixSymbols.get(symbol) : - HCPrefixes.AllBinaryPrefixSymbols.get(symbol) - ); - Name = GetName(Type, Factor); - } - else - { - Factor = 1.0; - Symbol = ""; - Name = ""; - } - } - - /** - Initialises a new Prefix instance. - @param name prefix Prefix variable whose information will be used. - **/ - public Prefix(Prefix prefix) - { - if (prefix == null) prefix = new Prefix(); - - Name = prefix.Name; - Symbol = prefix.Symbol; - Factor = prefix.Factor; - Type = prefix.Type; - PrefixUsage = prefix.PrefixUsage; - } - - private static PrefixTypes GetType(double factor, String symbol) - { - PrefixTypes outType = PrefixTypes.None; - if (factor == 1.0 && symbol == "") return outType; - - if (factor != 1.0) - { - if (HCPrefixes.AllSIPrefixes.containsValue(factor)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixes.containsValue(factor)) - { - outType = PrefixTypes.Binary; - } - } - else - { - if (HCPrefixes.AllSIPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.SI; - } - else if (HCPrefixes.AllBinaryPrefixSymbols.containsKey(symbol)) - { - outType = PrefixTypes.Binary; - } - } - - return outType; - } - - private static String GetName(PrefixTypes type, double factor) - { - return - ( - type == PrefixTypes.SI ? - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) : - Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().equals(new Double(factor)), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - ) - .getKey().toString(); - } - - @Override - ///Compares the current instance against another Prefix one. - ///The other Prefix instance. - public int compareTo(Prefix other) - { - return new Double(this.Factor).compareTo - ( - new Double(other.Factor) - ); - } - - @Override - ///Determines whether the current Prefix instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((Prefix)obj); - } - - boolean Equals(Prefix other) - { - return - ( - other == null ? false : - Equals.PrefixesAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this Prefix instance. - public int hashCode() { return 0; } - -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e6/a0ee75142a4c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e6/a0ee75142a4c00171ae7fcf2c321c986 deleted file mode 100644 index d0d8664..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e6/a0ee75142a4c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent); - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e7/20370d49f94c0017112184ad2ee33c77 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e7/20370d49f94c0017112184ad2ee33c77 deleted file mode 100644 index 2328c6f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e7/20370d49f94c0017112184ad2ee33c77 +++ /dev/null @@ -1,435 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix.equals(new UnitP(1.0, "ks").UnitPrefix)) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton).equals(new UnitP("1 Mg*m/s2"))) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e8/00675e045b4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e8/00675e045b4c0017146ede6da4ae5d42 deleted file mode 100644 index 11fc3d9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e8/00675e045b4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1179 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e8/e03423882a4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e8/e03423882a4a001712d4a4f7b050cac8 deleted file mode 100644 index a705ddb..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e8/e03423882a4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1164 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - System.out.println("asfasf"); - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e9/4092d5a9984a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e9/4092d5a9984a00171930ee4d171ed0de deleted file mode 100644 index 34ad7ac..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e9/4092d5a9984a00171930ee4d171ed0de +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e9/70200eb27e4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e9/70200eb27e4c00171945f16efe0d9b5d deleted file mode 100644 index 95b4c4c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e9/70200eb27e4c00171945f16efe0d9b5d +++ /dev/null @@ -1,102 +0,0 @@ -package InternalUnitParser.Operations; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class OperationsOther -{ - public static String GetOperationString(UnitP first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(UnitP first, Double second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), second.toString(), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(Double first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - first.toString(), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - private static String GetUnitPString(UnitP unitP) - { - return unitP.OriginalUnitString; - } - - private static String ConcatenateOperationString(String first, String second, char operation) - { - return (first + " " + operation + " " + second); - } - - //NOTE: the order within each char[] collection does matter. The first element will be treated as the default - //symbol for the given operation (e.g., used when creating a String including that operation). - public static HashMap> OperationSymbols; - - public static ArrayList UnitParseIgnored; - - public static final double MaxValue = 79228162514264337593543950335.0; //C# Decimal.MaxValue actual value. - public static final double MinValue = 0.0000000000000000000000000001; //C# Decimal precision lowest limit. - - public static String Start() - { - OperationSymbols = new HashMap>() - { - { - { - put - ( - Operations.Addition, new ArrayList() - {{ - add('+'); - }} - ); - put - ( - Operations.Subtraction, new ArrayList() - {{ - add('-'); add('−'); add('—'); - }} - ); - put - ( - Operations.Multiplication, new ArrayList() - {{ - add('*'); add('x'); add('X'); add('×'); add('⊗'); add('â‹…'); add('·'); - }} - ); - put - ( - Operations.Division, new ArrayList() - {{ - add('/'); - //add('/'); add('∕'); add('â„'); add('÷'); add('|'); add('\\'); - }} - ); - } - } - }; - - UnitParseIgnored = new ArrayList() - {{ - add("."); add(","); add(":"); add(";"); add("_"); add("^"); add("+"); - add("#"); add("("); add(")"); add("["); add("]"); add("{"); add("}"); - add("="); add("!"); add("?"); add("@"); add("&"); - }}; - - return ""; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e9/901b8475a94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e9/901b8475a94a00171059ebc16969059f deleted file mode 100644 index da7f5f0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/e9/901b8475a94a00171059ebc16969059f +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - System.out.println(parseInfo.UnitInfo.Parts.get(0).Unit + " " + parseInfo.UnitInfo.Parts.get(1).Unit); - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ea/602c59fe9c4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ea/602c59fe9c4a00171930ee4d171ed0de deleted file mode 100644 index bb52606..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ea/602c59fe9c4a00171930ee4d171ed0de +++ /dev/null @@ -1,1862 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - for(Double item: allPrefixes) - { - System.out.println(item); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> new Integer(x.getValue().compareTo(1.0)).equals(-1) - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ea/c07091a3c54a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ea/c07091a3c54a00171634abff01ee97d5 deleted file mode 100644 index 1c0daa4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ea/c07091a3c54a00171634abff01ee97d5 +++ /dev/null @@ -1,21 +0,0 @@ -package test0; - -import UnitParser.PrefixUsageTypes; -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - double test = 10 / 0.000000000000001; - test = test; - System.out.println(test); - //UnitP test = UnitP.Division - //( - // new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - // new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - //); - //System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ea/d062c7e8824c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ea/d062c7e8824c00171945f16efe0d9b5d deleted file mode 100644 index 212cab7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ea/d062c7e8824c00171945f16efe0d9b5d +++ /dev/null @@ -1,102 +0,0 @@ -package InternalUnitParser.Operations; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings("serial") -public class OperationsOther -{ - public static String GetOperationString(UnitP first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(UnitP first, Double second, Operations operation) - { - return ConcatenateOperationString - ( - GetUnitPString(first), second.toString(), OperationSymbols.get(operation).get(0) - ); - } - - public static String GetOperationString(Double first, UnitP second, Operations operation) - { - return ConcatenateOperationString - ( - first.toString(), GetUnitPString(second), OperationSymbols.get(operation).get(0) - ); - } - - private static String GetUnitPString(UnitP unitP) - { - return unitP.OriginalUnitString; - } - - private static String ConcatenateOperationString(String first, String second, char operation) - { - return (first + " " + operation + " " + second); - } - - //NOTE: the order within each char[] collection does matter. The first element will be treated as the default - //symbol for the given operation (e.g., used when creating a String including that operation). - public static HashMap> OperationSymbols; - - public static ArrayList UnitParseIgnored; - - public static final double MaxValue = 79228162514264337593543950335.0; //C# Decimal.MaxValue actual value. - public static final double MinValue = 0.0000000000000000000000000001; //C# Decimal precision lowest limit. - - public static String Start() - { - OperationSymbols = new HashMap>() - { - { - { - put - ( - Operations.Addition, new ArrayList() - {{ - add('+'); - }} - ); - put - ( - Operations.Subtraction, new ArrayList() - {{ - add('-'); add('−'); add('—'); - }} - ); - put - ( - Operations.Multiplication, new ArrayList() - {{ - add('*'); add('x'); add('X'); add('×'); add('⊗'); add('â‹…'); add('·'); - }} - ); - put - ( - Operations.Division, new ArrayList() - {{ - add('/'); add('â„'); add('÷'); - //add('/'); add('∕'); add('â„'); add('÷'); add('|'); add('\\'); - }} - ); - } - } - }; - - UnitParseIgnored = new ArrayList() - {{ - add("."); add(","); add(":"); add(";"); add("_"); add("^"); add("+"); - add("#"); add("("); add(")"); add("["); add("]"); add("{"); add("}"); - add("="); add("!"); add("?"); add("@"); add("&"); - }}; - - return ""; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ec/201612db5b4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ec/201612db5b4c0017146ede6da4ae5d42 deleted file mode 100644 index 9f4ecd6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ec/201612db5b4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,1201 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - ///Compares the current instance against another UnitP one. - ///The other UnitP instance. - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - ///Determines whether the current UnitP instance is equal to other one. - ///Other variable. - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - System.out.println("In Equals"); - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - ///Returns the hash code for this UnitP instance. - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ed/e09369bb2c4c00171ae7fcf2c321c986 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ed/e09369bb2c4c00171ae7fcf2c321c986 deleted file mode 100644 index 1f52e0f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ed/e09369bb2c4c00171ae7fcf2c321c986 +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = (int)Math.signum(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - System.out.println(sign); - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ee/303d884cc14a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ee/303d884cc14a00171634abff01ee97d5 deleted file mode 100644 index 043d029..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ee/303d884cc14a00171634abff01ee97d5 +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - System.out.println(first.ValueAndUnitString + " " + second.ValueAndUnitString); - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ee/d050c893b24b00171c69d98bf667dda6 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ee/d050c893b24b00171c69d98bf667dda6 deleted file mode 100644 index 009ec69..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ee/d050c893b24b00171c69d98bf667dda6 +++ /dev/null @@ -1,1383 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ee/d0e5a918314a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ee/d0e5a918314a001712d4a4f7b050cac8 deleted file mode 100644 index 63f8221..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ee/d0e5a918314a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1870 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - - Map.Entry res11 = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ); - - Map.Entry res12 = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ); - - - //Original C# code -> .ThenByDescending(x => x.Exponent) - int res2 = new Integer(second.Exponent).compareTo(first.Exponent); - if (res11 == null && res12 == null) - { - return res2; - } - - int res1 = res11.getValue().compareTo(res12.getValue()); - - return - ( - res11 != 0 ? res12 : res2 - ); - } - } - ); - - if(unitInfo.Parts.size() == 2) - { - System.out.println(unitInfo.Parts.get(0).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(0).Unit) + " -- " + unitInfo.Parts.get(1).Exponent + " " + unitInfo.InitialPositions.get(unitInfo.Parts.get(1).Unit)); - - } - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f/7024af44994a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f/7024af44994a00171930ee4d171ed0de deleted file mode 100644 index af231f7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f/7024af44994a00171930ee4d171ed0de +++ /dev/null @@ -1,1166 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - System.out.println(parseInfo.UnitInfo.Value + " " + parseInfo.UnitInfo.BaseTenExponent + " " + parseInfo.UnitInfo.Prefix.Factor); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP UnitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP UnitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - public boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - @Override - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /// - ///Adds two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Augend. In case of incompatibilities, its configuration would prevail. - ///Addend. - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /// - ///Subtracts two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Minuend. In case of incompatibilities, its configuration would prevail. - ///Subtrahend. - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /// - ///Multiplies two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Multiplicand. In case of incompatibilities, its configuration would prevail. - ///Multiplier. - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Multiplies a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /// - ///Divides two UnitP variables by giving preference to the configuration of the first operand. - ///Different unit types will trigger an error. - /// - ///Dividend. In case of incompatibilities, its configuration would prevail. - ///Divisor. - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /// - ///Divides the value of a UnitP variable by a double one. - ///Eventual errors will be managed as defined in first.ExceptionHandling. - /// - ///Dividend. - ///Divisor. - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - - /// - ///Divides a double variable by the value of a UnitP one. - ///Eventual errors will be managed as defined by the double type. - /// - ///Multiplicand. - ///Multiplier. - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f0/10cf4c4da84a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f0/10cf4c4da84a00171059ebc16969059f deleted file mode 100644 index 34ad7ac..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f0/10cf4c4da84a00171059ebc16969059f +++ /dev/null @@ -1,241 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f1/40b733eac54a00171634abff01ee97d5 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f1/40b733eac54a00171634abff01ee97d5 deleted file mode 100644 index 183338c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f1/40b733eac54a00171634abff01ee97d5 +++ /dev/null @@ -1,242 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - - System.out.println(first.ValueAndUnitString + " " + first.BaseTenExponent + " " + second.ValueAndUnitString); - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f1/70b767ff634c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f1/70b767ff634c0017146ede6da4ae5d42 deleted file mode 100644 index 04ad889..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f1/70b767ff634c0017146ede6da4ae5d42 +++ /dev/null @@ -1,436 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - System.out.println("Condition 1 true"); - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f4/40baf3b7bc4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f4/40baf3b7bc4a0017160ae291ab4667e2 deleted file mode 100644 index eab309e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f4/40baf3b7bc4a0017160ae291ab4667e2 +++ /dev/null @@ -1,430 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f4/b02342a08e4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f4/b02342a08e4a00171930ee4d171ed0de deleted file mode 100644 index 9d61c70..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f4/b02342a08e4a00171930ee4d171ed0de +++ /dev/null @@ -1,14 +0,0 @@ -package test0; - -import UnitParser.UnitP; -import UnitParser.UnitSymbols; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")); - //UnitP.Addition(UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ")); - System.out.println(test.UnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f5/6017a0e1b94a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f5/6017a0e1b94a0017160ae291ab4667e2 deleted file mode 100644 index 2b618b5..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f5/6017a0e1b94a0017160ae291ab4667e2 +++ /dev/null @@ -1,431 +0,0 @@ -package Parts; - -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - //Scanner scanner = new Scanner(System.in); - String input = "y"; //scanner.next(); - //System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - System.out.println("here"); - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f5/80fd0ee6a94a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f5/80fd0ee6a94a00171059ebc16969059f deleted file mode 100644 index d856eb9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f5/80fd0ee6a94a00171059ebc16969059f +++ /dev/null @@ -1,1382 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - System.out.println(parseInfo.UnitInfo.Value); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f6/90aaf481414c00171eb8e3cba3fc21fa b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f6/90aaf481414c00171eb8e3cba3fc21fa deleted file mode 100644 index bb1b329..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f6/90aaf481414c00171eb8e3cba3fc21fa +++ /dev/null @@ -1,84 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Locale; - -public class TryParseMethods -{ - public static TryParseOutput Double(String input) - { - TryParseOutput output = new TryParseOutput(); - - try - { - output.DoubleVal = ParseCommon(input).doubleValue(); - Double val = new Double(output.DoubleVal); - if(!(val.isNaN() || val.isInfinite())) - { - output.IsOK = true; - - String[] tempVar = CSharpOther.SplitTryCatch(input.toLowerCase(), "e"); - if (tempVar.length == 2) - { - if - ( - Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(tempVar[1]), x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { } - - return output; - } - - public static TryParseOutput Int(String input) - { - TryParseOutput output = new TryParseOutput(); - if (input.contains(".")) - { - //Emulating the conditions of the original C# version where decimal numbers cannot be parsed as integer. - return output; - } - - try - { - output.IntVal = ParseCommon(input).intValue(); - output.IsOK = true; - } - catch (Exception e) { } - - System.out.println(input + " " + output.IsOK); - - return output; - } - - static Number ParseCommon(String input) throws Exception - { - if - ( - input == null || Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(input.toLowerCase()), x -> !Character.isDigit(x) && - x != '.' && x != ',' && x != 'e' && x != '-' && x != '+', '\u0000' - ) - != '\u0000' - ) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - //Note that TryParseOutput analyses the exponential cases (i.e., including e + integer exponent) further. - throw new Exception(); - } - - return NumberFormat.getInstance(Locale.US).parse(input); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f6/f012f6dc9b4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f6/f012f6dc9b4a00171930ee4d171ed0de deleted file mode 100644 index 8e64f5a..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f6/f012f6dc9b4a00171930ee4d171ed0de +++ /dev/null @@ -1,1858 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - System.out.println(targetExponent); - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - //System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f7/100bd7555f4c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f7/100bd7555f4c0017146ede6da4ae5d42 deleted file mode 100644 index 2bccc56..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f7/100bd7555f4c0017146ede6da4ae5d42 +++ /dev/null @@ -1,17 +0,0 @@ -package test0; - -import UnitParser.UnitP; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP("1m"); - UnitP test2 = new UnitP(1.0, "m2/m"); - - if(test.equals(test2)) - { - System.out.println("Is OK"); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f9/b03625e42c4a001712d4a4f7b050cac8 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f9/b03625e42c4a001712d4a4f7b050cac8 deleted file mode 100644 index 186ae09..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/f9/b03625e42c4a001712d4a4f7b050cac8 +++ /dev/null @@ -1,1857 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - System.out.println(unitString); - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fa/60b49764b14a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fa/60b49764b14a00171059ebc16969059f deleted file mode 100644 index 35d8f1b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fa/60b49764b14a00171059ebc16969059f +++ /dev/null @@ -1,1055 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - System.out.println("here"); - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fa/d07dd211f74c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fa/d07dd211f74c00171048b3f61ecb42d3 deleted file mode 100644 index 0248192..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fa/d07dd211f74c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1239 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - @return UnitP variable containing all the unitP information without relying on the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0). - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - @return UnitP variable containing all the unitP information by reducing the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value as much as possible. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - @return Current instance converted to targetUnit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return Current instance converted to targetUnit and targetPrefix. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - @return Current instance converted to targetUnitString. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance unit. - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance unit. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance type. - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance type. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - @return ArrayList including all the primary string representations associated with the current instance type and system. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList including all the (primary or primary and secondary) string representations associated with the current instance type and system. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - @return ArrayList including all the units associated with the current instance type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - @return ArrayList including all the units associated with the current instance type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - @return UnitTypes variable associated with the current instance. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - @return UnitSystems variable associated with the current instance. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - @return Removes the global prefix (i.e., UnitP.UnitPrefix.Factor = 1.0) from the current instance. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @return Reduces the global base-ten exponent (i.e., UnitP.BaseTenExponent = 0) value of the current instance as much as possible. - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fa/e0f540dfb24a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fa/e0f540dfb24a00171059ebc16969059f deleted file mode 100644 index 19ba4bf..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fa/e0f540dfb24a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - System.out.println(outInfo.Value); - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fb/10310406954a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fb/10310406954a00171930ee4d171ed0de deleted file mode 100644 index 037910c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fb/10310406954a00171930ee4d171ed0de +++ /dev/null @@ -1,568 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.get(bigSmallI[0]).Value = big2.Value; - unitInfos2.get(bigSmallI[0]).BaseTenExponent = unitInfos2.get(bigSmallI[1]).BaseTenExponent; - - - System.out.println(unitInfos2.get(0).Value + " " + unitInfos2.get(0).BaseTenExponent + " " + unitInfos2.get(0).Prefix.Factor + " -- " + unitInfos2.get(1).Value + " " + unitInfos2.get(1).BaseTenExponent + " " + unitInfos2.get(1).Prefix.Factor); - - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - outInfo = - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - - return outInfo; - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fb/502949dd7a4c00171945f16efe0d9b5d b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fb/502949dd7a4c00171945f16efe0d9b5d deleted file mode 100644 index 95df9b9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fb/502949dd7a4c00171945f16efe0d9b5d +++ /dev/null @@ -1,1381 +0,0 @@ -package InternalUnitParser.Parse; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; - -/** -This class includes all the main parse-related code, stored in the original C# versions in the files under the Parse folder. -**/ -public class Parse -{ - public static ParseInfo StartUnitParse(ParseInfo parseInfo) - { - parseInfo = InitialParseActions(parseInfo); - return - ( - StringCanBeCompound(parseInfo.InputToParse) ? - StartCompoundParse(parseInfo) : - StartIndividualUnitParse(parseInfo) - ); - } - - static ParseInfo InitialParseActions(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null) parseInfo.InputToParse = ""; - parseInfo.InputToParse = parseInfo.InputToParse.trim(); - - if (parseInfo.InputToParse.length() < 1) - { - if (parseInfo.UnitInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - - return parseInfo; - } - - for (String ignored: OperationsOther.UnitParseIgnored) - { - parseInfo.InputToParse = parseInfo.InputToParse.replace(ignored, ""); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo, true); - - return parseInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = MethodsCommon.GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = MethodsCommon.GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - public static UnitInfo ParseDecimal(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - if (outVar.IsOK) - { - //In some cases, double.TryParse might consider valid numbers beyond the actual scope of - //double type. For example: 0.00000000000000000000000000000001m assumed to be zero. - if (outVar.DoubleVal != 0.0) - { - return ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal); - } - } - - return ParseDouble(stringToParse); - } - - static UnitInfo ParseDouble(String stringToParse) - { - TryParseOutput outVar = TryParseMethods.Double(stringToParse); - - return - ( - //Bear in mind that double.TryParse might misunderstand very small numbers, that's why 0.0 is treated as an error. - //GetInfoBeyondDouble will undoubtedly determine whether it is a real zero or not. - outVar.IsOK && outVar.DoubleVal != 0.0 ? - ExceptionInstantiation.NewUnitInfo(outVar.DoubleVal) : - GetInfoBeyondDouble(stringToParse) - ); - } - - //This method complements .NET numeric-type parsing methods beyond the double range (i.e., > 1e300). - static UnitInfo GetInfoBeyondDouble(String stringToParse) - { - stringToParse = stringToParse.toLowerCase(); - UnitInfo errorInfo = ExceptionInstantiation.NewUnitInfo(ErrorTypes.NumericError); - - TryParseOutput tempVar = null; - - //The double-parsing .NET format is expected. That is: only integer exponents after a - //letter "e", what indicates before-e * 10^after-e. - if (stringToParse.contains("e")) - { - String[] temp = CSharpOther.SplitTryCatch(stringToParse, "e"); - if (temp.length == 2) - { - if (temp[0].contains("e")) return errorInfo; - - UnitInfo outInfo = ParseDouble(temp[0]); - if (outInfo.Error.Type != ErrorTypes.None) - { - return errorInfo; - } - - tempVar = TryParseMethods.Int(temp[1]); - if (tempVar.IsOK) - { - outInfo.BaseTenExponent += tempVar.IntVal; - return outInfo; - } - } - } - else - { - if (stringToParse.length() < 300) - { - tempVar = TryParseMethods.Int(stringToParse); - if (tempVar.IsOK) - { - return ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal); - } - } - else - { - tempVar = TryParseMethods.Double(stringToParse.substring(0, 299)); - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - if (Linq.FirstOrDefault(CSharpOther.StringToCharacters(remString), x -> Character.isDigit(x) && !x.equals(','), '\u0000') != '\u0000') - { - //Finding a double separator here is considered an error because it wouldn't - //be too logical (300 digits before the double separator!). Mainly by bearing - //in mind the exponential alternative above. - return errorInfo; - } - - int beyondCount = GetBeyondDoubleCharacterCount(stringToParse.substring(299)); - if (beyondCount < 0) return errorInfo; - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = (Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1); - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, for the aforementioned double.TryParse, startNumber is zero. - boolean found = false; - int length2 = (remString.length() > 299 ? 299 : remString.length()); - for (int i = 0; i < remString.length(); i++) - { - if (remString.substring(i, 1) != "0" && remString.substring(i, 1) != ",") - { - //The default interpretation is initial_part*10^remString.size() (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, startNumber is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = Double.parseDouble(remString.substring(i, length2 - i)); - beyondCount = 297 + length2; - break; - } - } - - if (!found) return ExceptionInstantiation.NewUnitInfo(0.0); - } - - return Managed.VaryBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(tempVar.DoubleVal), sign * beyondCount - ); - } - } - } - - return errorInfo; - } - - static int GetBeyondDoubleCharacterCount(String remString) - { - int outCount = 0; - - try - { - for (char item: remString.toCharArray()) - { - if (!Character.isDigit(item) && item != ',') - { - return 0; - } - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting int.MaxValue. - outCount = -1; - } - - return outCount; - } - - static ParseInfo StartIndividualUnitParse(ParseInfo parseInfo) - { - return GetIndividualUnitParts - ( - ParseIndividualUnit(parseInfo) - ); - } - - static ParseInfo ParseIndividualUnit(ParseInfo parseInfo) - { - parseInfo = PrefixAnalysis(parseInfo); - - if (parseInfo.UnitInfo.Unit == Units.None) - { - //The final unit might have already been found while analysing prefixes. - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - - return parseInfo; - } - - static ParseInfo PrefixAnalysis(ParseInfo parseInfo) - { - parseInfo.UnitInfo.Unit = MethodsCommon.GetUnitFromString(parseInfo.InputToParse, parseInfo); - - return - ( - parseInfo.UnitInfo.Unit == Units.None ? - CheckPrefixes(parseInfo) : parseInfo - ); - } - - public static ParseInfo CheckPrefixes(ParseInfo parseInfo) - { - if (parseInfo.InputToParse.length() < 2) return parseInfo; - - String origString = parseInfo.InputToParse; - - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Prefix.PrefixUsage - ); - - ParseInfo tempSI = CheckSIPrefixes(new ParseInfo(parseInfo)); - ParseInfo tempBinary = CheckBinaryPrefixes(new ParseInfo(parseInfo)); - - if (tempSI.UnitInfo.Prefix.Factor != 1.0) - { - if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - //Both SI and binary prefixes were detected, what is an error. - parseInfo = new ParseInfo(); - parseInfo.InputToParse = origString; - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = new ParseInfo(tempSI); - } - else if (tempBinary.UnitInfo.Prefix.Factor != 1.0) - { - parseInfo = new ParseInfo(tempBinary); - } - - return parseInfo; - } - - static ParseInfo CheckBinaryPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.Binary); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.Binary, - HCPrefixes.AllBinaryPrefixSymbols, HCPrefixes.AllBinaryPrefixNames - ); - } - - static ParseInfo CheckSIPrefixes(ParseInfo parseInfo) - { - InitialisePrefixNames(PrefixTypes.SI); - - return CheckPrefixes - ( - parseInfo, PrefixTypes.SI, - HCPrefixes.AllSIPrefixSymbols, HCPrefixes.AllSIPrefixNames - ); - } - - static void InitialisePrefixNames(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllSIPrefixNames == null) - { - HCPrefixes.AllSIPrefixNames = (HashMap)HCPrefixes.AllSIPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllSIPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(SIPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - else if (prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.AllBinaryPrefixNames == null) - { - HCPrefixes.AllBinaryPrefixNames = (HashMap)HCPrefixes.AllBinaryPrefixSymbols.entrySet().stream().collect - ( - Collectors.toMap - ( - x -> x.getKey(), x -> Linq.FirstOrDefaultDict - ( - HCPrefixes.AllBinaryPrefixes, y -> y.getValue().equals(x.getValue()), - new AbstractMap.SimpleEntry(BinaryPrefixes.None, 0.0) - ) - .getKey().toString().toLowerCase() - ) - ); - } - } - } - - static ParseInfo CheckPrefixes(ParseInfo parseInfo, PrefixTypes prefixType, HashMap allPrefixes, HashMap allPrefixNames) - { - for (Map.Entry prefix: allPrefixes.entrySet()) - { - String remString = GetPrefixRemaining - ( - parseInfo.InputToParse, allPrefixNames.get(prefix.getKey()), prefix.getKey() - ); - if (remString == "") continue; - - ParseInfo parseInfo2 = AnalysePrefix - ( - parseInfo, prefixType, prefix, remString - ); - if (parseInfo2.UnitInfo.Unit != Units.None) - { - return parseInfo2; - } - } - - return parseInfo; - } - - static String GetPrefixRemaining(String input, String prefixName, String prefixSymbol) - { - String remString = GetPrefixRemainingSpecial - ( - input, prefixName, prefixSymbol - ); - if (remString != "") return remString; - - if (input.toLowerCase().startsWith(prefixName)) - { - //String representation. Case doesn't matter. - remString = input.substring(prefixName.length()); - } - else if (input.startsWith(prefixSymbol)) - { - //Symbol. Caps matter. - remString = input.substring(prefixSymbol.length()); - } - - return remString; - } - - //Accounts for cases where the default check (i.e., firstly name and then symbol) fails. - static String GetPrefixRemainingSpecial(String input, String prefixName, String prefixSymbol) - { - if (input.startsWith(prefixSymbol)) - { - if (input.toLowerCase().startsWith(prefixSymbol.toLowerCase() + "bit")) - { - //For example: Kibit which might be misunderstood as kibi prefix (name check) and t unit. - return "bit"; - } - } - - return ""; - } - - static ParseInfo AnalysePrefix(ParseInfo parseInfo, PrefixTypes prefixType, Map.Entry prefix, String remString) - { - Units unit = MethodsCommon.GetUnitFromString(remString); - - if (unit != Units.None) - { - parseInfo.UnitInfo.Unit = unit; - - if (MethodsCommon.PrefixCanBeUsedWithUnitBasicCheck(parseInfo.UnitInfo, prefixType)) - { - parseInfo.UnitInfo = UpdateUnitInformation - ( - parseInfo.UnitInfo, unit, new Prefix - ( - prefix.getValue(), parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - //Useful in case of looking for further prefixes. - parseInfo.InputToParse = remString; - } - } - - return parseInfo; - } - - static UnitInfo UpdateUnitInformation(UnitInfo unitInfo, Units unit, Prefix prefix) - { - unitInfo.Unit = unit; - unitInfo.Prefix = new Prefix(prefix); - unitInfo.Parts = MethodsCommon.GetUnitParts(unitInfo).Parts; - - return unitInfo; - } - - static ParseInfo GetIndividualUnitParts(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Unit == Units.None || parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (parseInfo.UnitInfo.Parts.size() == 0) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitParts(parseInfo.UnitInfo); - } - - if (parseInfo.UnitInfo.Parts.size() == 1) - { - boolean isCentimetre = parseInfo.UnitInfo.Parts.get(0).Unit == Units.Centimetre; - if(!isCentimetre) isCentimetre = - ( - parseInfo.UnitInfo.Parts.get(0).Unit == Units.Metre && - parseInfo.UnitInfo.Parts.get(0).Prefix.Factor == 0.01 - ); - - if(isCentimetre) - { - //Centimetre has a very special status: it is fully defined by centi+metre, but it also needs its - //own unit to be the CGS basic length unit. Formally, it is a compound (formed by 1 part); practically, - //it doesn't enjoy any of the benefits associated with this reality. - return parseInfo; - } - - //Parsing an individual unit might output more than 1 part. - if (parseInfo.UnitInfo.Parts.get(0).Prefix.Factor != 1.0) - { - //1 km should be understood as 1 metre with a kilo prefix, formed - //by one part of a metre (no prefix). - parseInfo.UnitInfo.Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix - ); - parseInfo.UnitInfo.Parts.get(0).Prefix = new Prefix - ( - parseInfo.UnitInfo.Parts.get(0).Prefix.PrefixUsage - ); - } - } - - return parseInfo; - } - - static ParseInfo StartCompoundParse(ParseInfo parseInfo) - { - //ValidCompound isn't used when parsing individual units. - parseInfo.ValidCompound = new StringBuilder(); - - return StartCompoundAnalysis - ( - ExtractUnitParts(parseInfo) - ); - } - - static ParseInfo ExtractUnitParts(ParseInfo parseInfo) - { - StringBuilder previous = new StringBuilder(); - String origInput = parseInfo.InputToParse; - - parseInfo = UnitInDenominator(parseInfo); - - //Both strings being different would mean that a number-only numerator was removed. - //For example: the input String 1/m is converted into m, but UpdateUnitParts treats - //it as m-1 because of isNumerator being false. - boolean isNumerator = (origInput == parseInfo.InputToParse); - - char symbol = ' '; - ArrayList inputArray = CSharpOther.StringToCharacters(parseInfo.InputToParse); - - for (int i = 0; i < inputArray.size(); i++) - { - char bit = inputArray.get(i); - - if (MethodsCommon.IsCompoundDescriptive(bit, true) && !SkipCompoundDescriptive(i, inputArray, previous.toString())) - { - if (bit == '-') - { - if (MinusIsOK(inputArray, i)) - { - previous.append(bit); - } - continue; - } - - parseInfo = UpdateUnitParts - ( - parseInfo, previous, isNumerator, symbol - ); - - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - - if (bit != '-') - { - symbol = bit; - if (OperationsOther.OperationSymbols.get(Operations.Division).contains(bit)) - { - isNumerator = false; - } - } - - previous = new StringBuilder(); - } - else previous.append(bit); - } - - return - ( - previous.length() == 0 ? parseInfo : - UpdateUnitParts(parseInfo, previous, isNumerator, symbol) - ); - } - - //Confirms whether the given minus sign (-) is correct. Any-5 is right, but 5-5 is wrong. - static boolean MinusIsOK(ArrayList inputArray, int i) - { - if (i > 0 && i < inputArray.size()) - { - if (Character.isDigit(inputArray.get(i + 1)) && !Character.isDigit(inputArray.get(i - 1))) - { - return true; - } - } - - return false; - } - - static boolean SkipCompoundDescriptive(int i, ArrayList inputArray, String sofar) - { - if (inputArray.get(i).toString().toLowerCase() == "x") - { - //By default, x is assumed to be a multiplication sign. - sofar = sofar.toLowerCase(); - - if (sofar.length() >= 2) - { - String sofar2 = sofar.substring(sofar.length() - 2, 2); - if (sofar2 == "ma" || sofar2 == "lu") - { - //It isn't a multiplication sign, but part of the String representations - //of maxwell or lux. - return true; - } - } - - if (sofar.length() >= 1) - { - String sofar2 = sofar.substring(sofar.length() - 1, 1); - if (sofar2 == "m" || sofar2 == "l") - { - if (i == inputArray.size() - 1 || MethodsCommon.IsCompoundDescriptive(inputArray.get(i + 1))) - { - //It isn't a multiplication sign, but part of the symbols Mx or lx. - return true; - } - } - } - } - - return false; - } - - //When parsing a unit, only integer exponents are considered valid numbers (e.g., m2). Inverse units - //(e.g., 1/m) are the exception to this rule. This method corrects the input String to avoid ExtractUnitParts - //to trigger an error. For example: 1/m*s being converted into m-1*s-1. - static ParseInfo UnitInDenominator(ParseInfo parseInfo) - { - for (Character symbol: OperationsOther.OperationSymbols.get(Operations.Division)) - { - String[] tempArray = CSharpOther.SplitTryCatch - ( - parseInfo.InputToParse, symbol.toString() - ); - - if (tempArray.length >= 2) - { - UnitInfo tempInfo = ParseDouble(tempArray[0]); - if (tempInfo.Value != 0.0 && tempInfo.Error.Type == ErrorTypes.None) - { - parseInfo.UnitInfo = Managed.PerformManagedOperationUnits - ( - parseInfo.UnitInfo, tempInfo, Operations.Multiplication - ); - parseInfo.InputToParse = parseInfo.InputToParse.substring - ( - tempArray[0].length() + symbol.toString().length() - ); - return parseInfo; - } - } - } - - return parseInfo; - } - - public static ParseInfo StartCompoundAnalysis(ParseInfo parseInfo) - { - if (parseInfo.UnitInfo.Error.Type != ErrorTypes.None) - { - return parseInfo; - } - if (parseInfo.ValidCompound == null) - { - parseInfo.ValidCompound = new StringBuilder(); - } - - parseInfo.UnitInfo = MethodsCommon.RemoveAllUnitInformation(parseInfo.UnitInfo); - - //Knowing the initial positions of all the unit parts is important because of the defining - //"first element rules" idea which underlies this whole approach. Such a determination isn't - //always straightforward due to the numerous unit part modifications. - parseInfo.UnitInfo = MethodsCommon.UpdateInitialPositions(parseInfo.UnitInfo); - - //This is the best place to determine the system before finding the unit, because the subsequent - //unit part corrections might provoke some misunderstandings on this front (e.g., CGS named - //compound divided into SI basic units). - parseInfo.UnitInfo.System = MethodsCommon.GetSystemFromUnitInfo(parseInfo.UnitInfo); - - //This is also an excellent place to correct eventual system mismatches. For example: N/pint - //where pint has to be converted into m3, the SI (first operand system) basic unit for volume. - parseInfo.UnitInfo = CorrectDifferentSystemIssues(parseInfo.UnitInfo); - - parseInfo.UnitInfo = MethodsCommon.ImproveUnitParts(parseInfo.UnitInfo); - - if (parseInfo.UnitInfo.Type == UnitTypes.None) - { - parseInfo.UnitInfo = MethodsCommon.GetUnitFromParts(parseInfo.UnitInfo); - } - - parseInfo.UnitInfo = UpdateMainUnitVariables(parseInfo.UnitInfo); - if (parseInfo.UnitInfo.Unit == Units.None) - { - parseInfo.UnitInfo.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else parseInfo = AnalyseValidCompoundInfo(parseInfo); - - return parseInfo; - } - - @SuppressWarnings("serial") - static UnitInfo CorrectDifferentSystemIssues(UnitInfo unitInfo) - { - UnitSystems basicSystem = HCMain.AllMetricEnglish.get(unitInfo.System); - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(1.0); - - for (int i = 1; i < unitInfo.Parts.size(); i++) - { - UnitPart part = unitInfo.Parts.get(i); - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(part); - UnitSystems system = MethodsCommon.GetSystemFromUnit(part.Unit, true); - //There are two different scenarios where a conversion might occur: metric vs. English or Imperial vs. USCS. - boolean convertEnglish = false; - - if (PartNeedsConversion(system, basicSystem, type) || (convertEnglish = PartNeedsConversionEnglish(unitInfo.System, MethodsCommon.GetSystemFromUnit(part.Unit)))) - { - UnitPart targetPart = GetTargetUnitPart - ( - unitInfo, part, type, - ( - convertEnglish ? unitInfo.System : basicSystem - ) - ); - - if (targetPart == null || targetPart.Unit == part.Unit || MethodsCommon.GetTypeFromUnitPart(targetPart) != type) - { - continue; - } - - UnitInfo tempInfo = Conversions.AdaptUnitParts - ( - ExceptionInstantiation.NewUnitInfo - ( - 1.0, new ArrayList() - {{ - add(part); add(targetPart); - }} - ), - 0, 1 - ); - - if (tempInfo == null) continue; - //AdaptUnitParts doesn't perform an actual conversion, just an adaptation to the target format. - //That's why it doesn't account for the target prefix, what explains the modification below. - tempInfo.Parts.get(0).Prefix = new Prefix(targetPart.Prefix); - - unitInfo = UpdateNewUnitPart - ( - unitInfo, unitInfo.Parts.get(i), - tempInfo.Parts.get(0) - ); - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, tempInfo, Operations.Multiplication - ); - } - } - - return Managed.PerformManagedOperationUnits - ( - unitInfo, convertInfo, Operations.Multiplication - ); - } - - static UnitPart GetTargetUnitPart(UnitInfo unitInfo, UnitPart part, UnitTypes partType, UnitSystems targetSystem) - { - for (UnitPart part2: unitInfo.Parts) - { - if (part2.Unit == part.Unit) continue; - - if (MethodsCommon.GetSystemFromUnit(part2.Unit) == targetSystem && MethodsCommon.GetTypeFromUnitPart(part2, true) == partType) - { - //Different unit part with the same type and the target system is good enough. - //For example: in kg/m*ft, m is a good target for ft. - return new UnitPart(part2) - {{ - //The exponent is removed because there was a non-exponent match. - //Cases like m3-litre never reach this point and are analysed below. - Exponent = 1; - }}; - } - } - - return GetBasicUnitPartForTypeSystem(partType, targetSystem); - } - - static boolean PartNeedsConversionEnglish(UnitSystems system1, UnitSystems system2) - { - return - ( - (system1 == UnitSystems.USCS || system2 == UnitSystems.USCS) && system1 != system2 - ); - } - - static boolean PartNeedsConversion(UnitSystems partSystem, UnitSystems basicSystem, UnitTypes partType) - { - if (HCOther.NeutralTypes.contains(partType)) return false; - - return - ( - partSystem == UnitSystems.None || basicSystem == UnitSystems.None ? - true : HCMain.AllMetricEnglish.get(partSystem) != basicSystem - ); - } - - static UnitInfo UpdateNewUnitPart(UnitInfo unitInfo, UnitPart oldUnitPart, UnitPart newUnitPart) - { - int newPos = 0; - Map.Entry oldPos = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(oldUnitPart), - new AbstractMap.SimpleEntry(null, 0) - ); - - if (oldPos.getKey() != null) - { - newPos = oldPos.getValue(); - HashMap allOccurrences = Linq.WhereDict - ( - unitInfo.InitialPositions, x -> x.getValue().equals(oldPos.getValue()) - ); - - for (Map.Entry item: allOccurrences.entrySet()) - { - unitInfo.InitialPositions.remove(item.getKey()); - } - } - else if (unitInfo.InitialPositions.size() > 0) - { - newPos = Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue(); - } - - if (!unitInfo.InitialPositions.containsKey(newUnitPart)) - { - unitInfo.InitialPositions.put(newUnitPart, newPos); - } - - unitInfo.Parts.remove(oldUnitPart); - unitInfo.Parts.add(new UnitPart(newUnitPart)); - - return unitInfo; - } - - static UnitPart GetBasicUnitPartForTypeSystem(UnitTypes type, UnitSystems system) - { - if (HCCompounds.AllBasicUnits.containsKey(type) && HCCompounds.AllBasicUnits.get(type).containsKey(system)) - { - //The given type/system matches a basic unit. For example: length and SI matching metre. - Units unit2 = HCCompounds.AllBasicUnits.get(type).get(system).Unit; - if (MethodsCommon.UnitIsNamedCompound(unit2)) - { - //Note that BasicUnit doesn't fully agree with the "basic unit" concept and that's why it might - //be a compound. - ArrayList compoundUnitParts = MethodsCommon.GetBasicCompoundUnitParts(unit2, true); - if (compoundUnitParts.size() == 1) - { - //Only 1-unit-part versions are relevant. - //This condition should always be met as far as all the compound basic units are expected to - //have a 1-unit-part version. For example: energy defined as an energy unit part. - //This theoretically-never-met condition accounts for eventual hardcoding misconducts, like - //faulty population of AllCompounds. - return new UnitPart(compoundUnitParts.get(0)); - } - } - else - { - return UnitPartInternal.NewUnitPart - ( - HCCompounds.AllBasicUnits.get(type).get(system).Unit, - HCCompounds.AllBasicUnits.get(type).get(system).PrefixFactor, - //Note that exponents aren't relevant to define basic units (= always 1). - //On the other hand, they might be formed by parts where the exponent is - //relevant; for example: Units.CubicMetre (1 part with exponent 3). - 1 - ); - } - } - - ArrayList unitParts = MethodsCommon.GetBasicCompoundUnitParts(type, system, true); - return - ( - unitParts.size() != 1 ? null : - //Type and system match a basic compound consisting in just one part (e.g., m2). - new UnitPart(unitParts.get(0)) - ); - } - - //Making sure that the assumed-valid compound doesn't really hide invalid information. - static ParseInfo AnalyseValidCompoundInfo(ParseInfo parseInfo) - { - if (parseInfo.InputToParse == null || parseInfo.ValidCompound.length() < 1) - { - //This part might be reached when performing different actions than parsing; that's why - //InputToParse or ValidCompound might have not be populated. - return parseInfo; - } - - ArrayList valid = CSharpOther.StringToCharacters(parseInfo.ValidCompound.toString()); - ArrayList toCheck = Linq.Where - ( - CSharpOther.StringToCharacters(parseInfo.InputToParse.trim()), x -> !x.equals(' ') - ); - - if (valid.size() == toCheck.size()) return parseInfo; - - double invalidCount = 0.0; - int i2 = -1; - - for (int i = 0; i < toCheck.size(); i++) - { - i2 = i2 + 1; - if (i2 > valid.size() - 1) break; - - if (!CharAreEquivalent(valid.get(i2), toCheck.get(i))) - { - if (!wrongCharIsOK(toCheck.get(i))) - { - invalidCount = invalidCount + 1.0; - } - i = i + 1; - } - } - - if (invalidCount >= 3.0 || invalidCount / valid.size() >= 0.25) - { - parseInfo.UnitInfo.Type = UnitTypes.None; - parseInfo.UnitInfo.Unit = Units.None; - } - - return parseInfo; - } - - static boolean CharAreEquivalent(Character char1, Character char2) - { - if (char1 == char2) return true; - - return (char1.toString().toLowerCase() == char2.toString().toLowerCase()); - } - - //Certain symbols aren't considered when post-analysing the validity of the input String. - //For example: m//////////////s is considered fine. - static boolean wrongCharIsOK(Character charToCheck) - { - if (HCOther.UnitParseIgnored.contains(charToCheck.toString())) - { - return true; - } - - for (Map.Entry> item: OperationsOther.OperationSymbols.entrySet()) - { - if (item.getValue().contains(charToCheck)) - { - return true; - } - } - - return false; - } - - //Instrumental class whose sole purpose is easing the exponent parsing process. - static class ParseExponent - { - public String AfterString; - public int Exponent; - - public ParseExponent(String afterString) - { - this(afterString, 1); - } - public ParseExponent(String afterString, int exponent) - { - AfterString = afterString; - Exponent = exponent; - } - } - - /* - Returns the String representation of the unit associated with the given compound. - NOTE: this function assumes that a valid compound is already in place. - */ - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - int exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + new Integer(exponent).toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - public static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = MethodsCommon.GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = MethodsCommon.GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = MethodsCommon.SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - 1.0, unitParts - ); - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = MethodsCommon.GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = MethodsCommon.GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - return true; - } - - static ParseExponent AnalysePartExponent(String input) - { - input = input.trim(); - char[] inputArray = input.toCharArray(); - int i2 = 0; - - for (int i = input.length() - 1; i >= 0; i--) - { - if (!Character.isDigit(inputArray[i]) && inputArray[i] != '-') - { - i2 = i; - break; - } - } - - ParseExponent outVar = new ParseExponent(input); - TryParseOutput tempVar = TryParseMethods.Int(input.substring(i2 + 1)); - - if (tempVar.IsOK) - { - //Only integer exponents are supported. - outVar = new ParseExponent - ( - input.substring(0, i2 + 1), tempVar.IntVal - ); - } - - return outVar; - } - - static ParseInfo UpdateUnitParts(ParseInfo parseInfo, StringBuilder inputSB, boolean isNumerator, char symbol) - { - if (inputSB.length() == 0) return parseInfo; - String input = inputSB.toString(); - - ParseExponent exponent = AnalysePartExponent(input); - if (!isNumerator) exponent.Exponent = -1 * exponent.Exponent; - - ParseInfo parseInfo2 = StartIndividualUnitParse - ( - new ParseInfo - ( - 0.0, exponent.AfterString, - parseInfo.UnitInfo.Prefix.PrefixUsage - ) - ); - - return - ( - parseInfo2.UnitInfo.Unit == Units.None ? - new ParseInfo(parseInfo) - {{ - UnitInfo = ExceptionInstantiation.NewUnitInfo - ( - parseInfo.UnitInfo, ErrorTypes.InvalidUnit - ); - }} : - AddValidUnitPartInformation - ( - parseInfo, parseInfo2, symbol, exponent, input - ) - ); - } - - @SuppressWarnings("serial") - static ParseInfo AddValidUnitPartInformation(ParseInfo parseInfo, ParseInfo parseInfo2, char symbol, ParseExponent exponent, String input) - { - parseInfo.ValidCompound = AddInformationToValidCompound - ( - parseInfo.ValidCompound, symbol, exponent, input - ); - - parseInfo.UnitInfo = MethodsCommon.AddNewUnitParts - ( - parseInfo.UnitInfo, new ArrayList() - {{ - add - ( - UnitPartInternal.NewUnitPart - ( - parseInfo2.UnitInfo.Unit, parseInfo2.UnitInfo.Prefix.Factor, - exponent.Exponent - ) - ); - }} - ); - - return parseInfo; - } - - static StringBuilder AddInformationToValidCompound(StringBuilder validCompound, char symbol, ParseExponent exponent, String input) - { - if (symbol != ' ') validCompound.append(symbol); - - if (exponent.AfterString.trim().length() > 0) - { - validCompound.append(exponent.AfterString); - } - - String exponent2 = input.replace(exponent.AfterString, "").trim(); - if (exponent2.length() > 0) - { - validCompound.append(exponent2); - } - - return validCompound; - } - - static boolean StringCanBeCompound(String inputToParse) - { - return - ( - inputToParse.length() >= 2 && Linq.FirstOrDefault - ( - CSharpOther.StringToCharacters(inputToParse), - x -> MethodsCommon.IsCompoundDescriptive(x), '\u0000' - ) - != '\u0000' - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fb/60fd0fc6a74a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fb/60fd0fc6a74a00171059ebc16969059f deleted file mode 100644 index a79bef9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fb/60fd0fc6a74a00171059ebc16969059f +++ /dev/null @@ -1,13 +0,0 @@ -package test0; - -import UnitParser.UnitP; -import UnitParser.Units; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft")); - System.out.println(test.ValueAndUnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/109f784cbc4a0017160ae291ab4667e2 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/109f784cbc4a0017160ae291ab4667e2 deleted file mode 100644 index a47b422..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/109f784cbc4a0017160ae291ab4667e2 +++ /dev/null @@ -1,444 +0,0 @@ -package Parts; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.Scanner; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if (new UnitP("1 N") == new UnitP(1.0, UnitSymbols.Newton) && new UnitP(1.0, UnitSymbols.Newton) == new UnitP(1.0, "nEwTon") && new UnitP(1.0, "nEwTon") == new UnitP(Units.Newton)) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec") == UnitP.Division(new UnitP("1 m"), new UnitP("s")) && new UnitP("1 N") == new UnitP("1 kg*m/s2")) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 Jâ‹…s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - String input = ""; - - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - try - { - input = br.readLine(); - } catch (IOException e) - { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - //Scanner scanner = new Scanner(System.in); - - //System.out.println(input); - if (input.toLowerCase() == "y") - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - //scanner.next(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - //scanner.next(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error == null || unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " : // + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/3099138e8e4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/3099138e8e4a00171930ee4d171ed0de deleted file mode 100644 index 810f3e0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/3099138e8e4a00171930ee4d171ed0de +++ /dev/null @@ -1,13 +0,0 @@ -package test0; - -import UnitParser.UnitP; -import UnitParser.UnitSymbols; - -public class Main -{ - public static void main(String[] args) throws Exception - { - UnitP test = new UnitP(1.0, UnitSymbols.Rod + "/h2"); - System.out.println(test.UnitString); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/5023397ca84a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/5023397ca84a00171059ebc16969059f deleted file mode 100644 index bf105d7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/5023397ca84a00171059ebc16969059f +++ /dev/null @@ -1,246 +0,0 @@ -package InternalUnitParser.Operations; - -import java.util.ArrayList; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Parse.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -public class OperationsPublic -{ - public static UnitP PerformUnitOperation(UnitP first, UnitP second, Operations operation, String operationString) - { - ErrorTypes errorType = MethodsErrors.GetUnitOperationError(first, second, operation); - if (errorType != ErrorTypes.None) - { - return new UnitP(first, errorType); - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - UnitInfo secondInfo = ExceptionInstantiation.NewUnitInfo(second); - - if (outInfo.Unit != Units.Unitless && secondInfo.Unit != Units.Unitless) - { - if (operation == Operations.Addition || operation == Operations.Subtraction) - { - UnitInfo[] tempInfos = PerformChecksBeforeAddition(outInfo, secondInfo); - - for (UnitInfo tempInfo: tempInfos) - { - if (tempInfo.Error.Type != ErrorTypes.None) - { - return new UnitP(first, tempInfo.Error.Type); - } - } - //Only the second operator might have been modified. - secondInfo = tempInfos[1]; - } - else outInfo = ModifyUnitPartsBeforeMultiplication(first, secondInfo, operation); - } - else if (outInfo.Unit == Units.Unitless && secondInfo.Unit != Units.Unitless) - { - outInfo = UnitlessAndUnitBeforeOperation - ( - outInfo, secondInfo, operation - ); - } - System.out.println - ( - outInfo.Value + " " + outInfo.BaseTenExponent + " " + outInfo.Prefix.Factor + " -- " + - secondInfo.Value + " " + secondInfo.BaseTenExponent + " " + secondInfo.Prefix.Factor - ); - - if (outInfo.Error.Type != ErrorTypes.None || outInfo.Unit == Units.None) - { - return new UnitP - ( - first, - ( - outInfo.Error.Type != ErrorTypes.None ? - outInfo.Error.Type : ErrorTypes.InvalidUnit - ) - ); - } - - outInfo = Managed.PerformManagedOperationUnits(outInfo, secondInfo, operation); - - return - ( - outInfo.Error.Type != ErrorTypes.None ? - new UnitP(first, outInfo.Error.Type) : - new UnitP - ( - outInfo, first, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo UnitlessAndUnitBeforeOperation(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - outInfo = ExceptionInstantiation.NewUnitInfo - ( - secondInfo, outInfo.Value, outInfo.BaseTenExponent, new Prefix(outInfo.Prefix) - ); - - if (operation == Operations.Division) - { - outInfo = MethodsCommon.GetUnitFromParts - ( - MethodsCommon.RemoveAllUnitInformation(MethodsCommon.InverseUnit(outInfo)) - ); - } - - return outInfo; - } - - static UnitInfo[] PerformChecksBeforeAddition(UnitInfo outInfo, UnitInfo secondInfo) - { - UnitInfo[] outInfos = new UnitInfo[] { outInfo, secondInfo }; - - if (outInfo.Type != secondInfo.Type) - { - outInfos[0].Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - } - else if (outInfo.Unit != secondInfo.Unit || MethodsCommon.IsUnnamedUnit(outInfo.Unit)) - { - outInfos[1] = Conversions.ConvertUnit(secondInfo, outInfo, false); - } - - return outInfos; - } - - static UnitInfo ModifyUnitPartsBeforeMultiplication(UnitP first, UnitInfo secondInfo, Operations operation) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(first); - ArrayList parts2 = new ArrayList(); - int sign = (operation == Operations.Multiplication ? 1 : -1); - - for (UnitPart part: secondInfo.Parts) - { - parts2.add - ( - new UnitPart(part) - {{ - Exponent = part.Exponent * sign; - }} - ); - } - - outInfo = MethodsCommon.AddNewUnitParts(outInfo, parts2); - - return Parse.StartCompoundAnalysis - ( - new ParseInfo(outInfo) - ) - .UnitInfo; - } - public static UnitP PerformUnitOperation(UnitP first, double secondValue, Operations operation, String operationString) - { - return PerformUnitValueOperation - ( - first, ExceptionInstantiation.NewUnitInfo(first), - ExceptionInstantiation.NewUnitInfo(secondValue), - operation, operationString - ); - } - - public static UnitP PerformUnitOperation(double firstValue, UnitP second, Operations operation, String operationString) - { - //The first operand (the one defining exception handling) is a number and that's why exceptions have to be left unhandled. - UnitP second2 = new UnitP(second, ErrorTypes.None, ExceptionHandlingTypes.AlwaysTriggerException); - - return PerformUnitValueOperation - ( - second2, ExceptionInstantiation.NewUnitInfo(firstValue), - ExceptionInstantiation.NewUnitInfo(second), operation, operationString - ); - } - - static UnitP PerformUnitValueOperation(UnitP unitP, UnitInfo firstInfo, UnitInfo secondInfo, Operations operation, String operationString) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo - ( - firstInfo, unitP.Unit, new ArrayList(unitP.UnitParts) - ); - - outInfo.Error = ExceptionInstantiation.NewErrorInfo - ( - MethodsErrors.GetUnitValueOperationError - ( - unitP, firstInfo, secondInfo, operation - ) - ); - - if (outInfo.Error.Type == ErrorTypes.None) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, secondInfo, operation - ); - - if (operation == Operations.Division && secondInfo.Unit != Units.None && secondInfo.Unit != Units.Unitless) - { - if (outInfo.Parts.size() > 0) - { - //value/unit is the only scenario value-unit operation where the unit - //information needs further analysis. - - outInfo = Parse.StartCompoundAnalysis - ( - new ParseInfo - ( - InversePrefix(MethodsCommon.InverseUnit(outInfo)) - ) - ) - .UnitInfo; - } - } - } - - return - ( - outInfo.Error.Type != ErrorTypes.None ? new UnitP(unitP, outInfo.Error.Type) : - new UnitP - ( - outInfo, unitP, operationString, - ( - //Multiplication/division are likely to provoke situations requiring a correction; - //for example, 1/(1/60) being converted into 60. On the other hand, cases like - //1.0 - 0.000001 shouldn't be changed (e.g., converting 0.999999 to 1.0 is wrong). - operation == Operations.Multiplication || - operation == Operations.Division - ) - ) - ); - } - - static UnitInfo InversePrefix(UnitInfo outInfo) - { - if (outInfo.Prefix.Factor == 1.0) return outInfo; - - outInfo = ExceptionInstantiation.NewUnitInfo - ( - outInfo, new Prefix(outInfo.Prefix.PrefixUsage) - ); - - //No need to find a new prefix. - return Managed.PerformManagedOperationUnits - ( - outInfo, Managed.PerformManagedOperationValues - ( - 1.0, outInfo.Prefix.Factor, Operations.Division - ), - Operations.Multiplication - ); - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/805398889b4a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/805398889b4a00171930ee4d171ed0de deleted file mode 100644 index 4e5676c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fc/805398889b4a00171930ee4d171ed0de +++ /dev/null @@ -1,1858 +0,0 @@ -package InternalUnitParser.Methods; - -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; -import InternalUnitParser.CSharpAdaptation.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Comparator; - -/** -Class including various methods used in internal calculations and spread across different files in the original C# code. -**/ -@SuppressWarnings("serial") -public class MethodsCommon -{ - public static Units GetUnitFromString(String input) - { - return GetUnitFromString(input, null); - } - - public static Units GetUnitFromString(String input, ParseInfo parseInfo) - { - Units unit = GetUnitFromUnitSymbols(input); - - return - ( - unit != Units.None ? unit : - GetUnitFromUnitStrings(input, parseInfo) - ); - } - - static Units GetUnitFromUnitSymbols(String input) - { - return - ( - HCUnits.AllUnitSymbols.containsKey(input) ? - HCUnits.AllUnitSymbols.get(input) : - GetUnitFromUnitSymbols2(input) - ); - } - - static Units GetUnitFromUnitSymbols2(String input) - { - return - ( - HCMain.AllUnitSymbols2.containsKey(input) ? - HCMain.AllUnitSymbols2.get(input) : Units.None - ); - } - - static Units GetUnitFromUnitStrings(String input, ParseInfo parseInfo) - { - String inputLower = input.toLowerCase(); - - Units unit = Units.None; - try - { - unit = Linq.FirstOrDefaultDict - ( - HCMain.AllUnitStrings, x -> - ( - x.getKey().toLowerCase().equals(inputLower) || - GetUnitStringPlural(x.getKey().toLowerCase()).equals(inputLower) - ), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getValue(); - } - catch(Exception e) - { - //This part will never be hit as far as FirstOrDefaultDict takes care of all the possible scenarios. - //The only motivation for this try...catch is complying in the Java requirements - } - - if (parseInfo != null && unit != Units.None) - { - //To account for somehow unlikely scenarios where non-official abbreviations are - //misinterpreted. For example, Gs misunderstood as grams rather than as gigasecond. - ParseInfo temp = Parse.CheckPrefixes(parseInfo); - if (temp.UnitInfo.Unit != Units.None) - { - //The unit (+ prefix) will be adequately analysed somewhere else. - return Units.None; - } - } - - return unit; - } - - public static boolean IsUnnamedUnit(Units unit) - { - return - ( - unit == Units.ValidImperialUnit || - HCMain.DefaultUnnamedUnits.containsValue(unit) - ); - } - - //A proper plural determination isn't required. The outputs of this method are quite secondary and - //the supported units quite regular on this front. - static String GetUnitStringPlural(String unitString) - { - if (unitString.endsWith("y")) - { - return unitString.substring(0, unitString.length() - 1) + "ies"; - } - unitString = unitString.replace("inches", "inch"); - unitString = unitString.replace("inch", "inches"); - unitString = unitString.replace("foot", "feet"); - - return - ( - unitString.endsWith("inches") || unitString.endsWith("feet") ? - unitString : unitString + "s" - ); - } - - public static String GetUnitString(UnitInfo unitInfo) - { - String outUnit = GetUnitStringIndividual(unitInfo); - - return - ( - outUnit == "None" ? - GetUnitStringCompound(unitInfo) : outUnit - ); - } - - //Returns the string representation of the unit associated with the given compound. - //NOTE: this function assumes that a valid compound is already in place. - static String GetUnitStringCompound(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None) return "None"; - else if (unitInfo.Unit == Units.Unitless) return "Unitless"; - - String outUnitString = ""; - boolean isNumerator = true; - - for (UnitPart unitPart: unitInfo.Parts) - { - if (isNumerator && unitPart.Exponent < 0) - { - isNumerator = false; - if (outUnitString == "") outUnitString = "1"; - outUnitString = outUnitString + "/"; - } - else if (outUnitString != "") outUnitString = outUnitString + "*"; - - String unitString = ""; - if (unitPart.Prefix.Symbol != "" && !unitPart.Unit.toString().toLowerCase().startsWith(unitPart.Prefix.Name.toLowerCase())) - { - unitString = unitPart.Prefix.Symbol; - } - unitString += Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitPart.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - Integer exponent = Math.abs(unitPart.Exponent); - if (exponent != 1) unitString = unitString + exponent.toString(); - - outUnitString = outUnitString + unitString; - } - - return outUnitString; - } - - static String GetUnitStringIndividual(UnitInfo unitInfo) - { - String unitString = "None"; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - if (HCUnits.AllUnitSymbols.containsValue(unitInfo.Unit)) - { - unitString = Linq.FirstOrDefaultDict - ( - HCUnits.AllUnitSymbols, x -> x.getValue().equals(unitInfo.Unit), - new AbstractMap.SimpleEntry(null, Units.None) - ) - .getKey(); - - if (unitInfo.Prefix.Symbol != "") - { - unitString = unitInfo.Prefix.Symbol + unitString; - } - } - } - - return unitString; - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo) - { - return RemoveAllUnitInformation(unitInfo, false); - } - - public static UnitInfo RemoveAllUnitInformation(UnitInfo unitInfo, boolean partsToo) - { - unitInfo.Unit = Units.None; - unitInfo.System = UnitSystems.None; - unitInfo.Type = UnitTypes.None; - - if (partsToo) unitInfo.Parts = new ArrayList(); - - return unitInfo; - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart) - { - return GetTypeFromUnitPart(unitPart, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents) - { - return GetTypeFromUnitPart(unitPart, ignoreExponents, false); - } - - public static UnitTypes GetTypeFromUnitPart(UnitPart unitPart, boolean ignoreExponents, boolean simplestApproach) - { - UnitPart unitPart2 = new UnitPart(unitPart); - - if (simplestApproach) - { - //This is reached when calling from parts of the code likely to provoke an infinite loop. - UnitTypes type2 = GetTypeFromUnit(unitPart2.Unit); - - if (type2 == UnitTypes.Length) - { - if (unitPart2.Exponent == 2) - { - type2 = UnitTypes.Area; - } - else if (unitPart2.Exponent == 3) - { - type2 = UnitTypes.Volume; - } - } - - return type2; - } - - //When comparing unit part types, the exponent is often irrelevant. For example: in the compound - //kg*m4, looking for m4 would yield no match (unlikely looking just for m). - if (ignoreExponents) unitPart2.Exponent = 1; - - //Negative exponents do not affect type determination. For example, a unit consisting - //in just the part m-1 is wavenumber (negative exponent being relevant), but is expected - //to be treated as length (-1 doesn't matter) because of being used in internal calculations. - unitPart2.Exponent = Math.abs(unitPart2.Exponent); - UnitInfo unitInfo = null; - try - { - unitInfo = new UnitInfo(unitPart2.Unit, unitPart2.Prefix.Factor); - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - unitInfo.Parts = new ArrayList() {{ add(unitPart2); }}; - - UnitTypes outType = GetTypeFromUnitInfo(unitInfo); - return - ( - outType == UnitTypes.None && unitPart2.Exponent != 1 ? - //To account for cases like kg4 within compounds, expected to be understood as kg. - GetTypeFromUnitPart(new UnitPart(unitPart2) {{ this.Exponent = 1; }}) : outType - ); - } - - public static UnitTypes GetTypeFromUnitInfo(UnitInfo unitInfo) - { - UnitTypes outType = UnitTypes.None; - if (unitInfo.Parts.size() > 1 || Linq.FirstOrDefault(unitInfo.Parts, x -> !x.Exponent.equals(1), null) != null) - { - outType = GetBasicCompoundType(unitInfo).Type; - } - - return - ( - outType != UnitTypes.None ? - outType : GetTypeFromUnit(unitInfo.Unit) - ); - } - - public static UnitTypes GetTypeFromUnit(Units unit) - { - return - ( - unit == Units.None || unit == Units.Unitless || IsUnnamedUnit(unit) ? - UnitTypes.None : HCMain.AllUnitTypes.get(unit) - ); - } - - public static UnitSystems GetSystemFromUnit(Units unit) - { - return GetSystemFromUnit(unit, false, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion) - { - return GetSystemFromUnit(unit, getBasicVersion, false); - } - - public static UnitSystems GetSystemFromUnit(Units unit, boolean getBasicVersion, boolean getImperialAndUSCS) - { - if (unit == Units.None || unit == Units.Unitless) - { - return UnitSystems.None; - } - - UnitSystems system = HCMain.AllUnitSystems.get((Units)unit); - - if (getImperialAndUSCS) - { - if (system == UnitSystems.Imperial && HCUnits.AllImperialAndUSCSUnits.contains(unit)) - { - system = UnitSystems.ImperialAndUSCS; - } - } - - return - ( - getBasicVersion ? HCMain.AllBasicSystems.get(system) : system - ); - } - - public static HashMap GetInitialPositions(ArrayList unitParts) - { - HashMap outDict = new HashMap(); - - for (int i = 0; i < unitParts.size(); i++) - { - if (!outDict.containsKey(unitParts.get(i))) - { - outDict.put(unitParts.get(i), i); - } - } - - return outDict; - } - - public static UnitInfo GetBasicCompoundType(UnitInfo unitInfo) - { - for (Map.Entry> allCompound: HCCompounds.AllCompounds.entrySet()) - { - for (Compound compound: allCompound.getValue()) - { - unitInfo = UnitPartsMatchCompound - ( - unitInfo, compound.Parts, allCompound.getKey() - ); - - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - } - - return unitInfo; - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo) - { - return UpdateMainUnitVariables(unitInfo, false); - } - - public static UnitInfo UpdateMainUnitVariables(UnitInfo unitInfo, boolean recalculateAlways) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless) - { - return unitInfo; - } - - if (recalculateAlways) - { - unitInfo.Type = UnitTypes.None; - unitInfo.System = UnitSystems.None; - } - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnitInfo(unitInfo); - } - - return unitInfo; - } - - static UnitInfo UnitPartsMatchCompound(UnitInfo unitInfo, ArrayList compoundParts, UnitTypes compoundType) - { - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundComparisonUnitParts(unitInfo, count); - if (UnitPartsMatchCompoundParts(unitParts, compoundParts)) - { - unitInfo.Type = compoundType; - return unitInfo; - } - else if (count == 2 && unitParts.size() == 1 && unitParts.get(0).Exponent == 1) - { - UnitTypes type = GetTypeFromUnit(unitParts.get(0).Unit); - if (type != UnitTypes.None) - { - //The modifications in GetCompoundComparisonUnitParts generated an individual unit. - //It might not be recognised anywhere else, so better taken care of it here. - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - unitInfo.Type = type; - - return unitInfo; - } - } - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundParts(ArrayList unitParts, ArrayList compoundParts) - { - if (unitParts.size() != compoundParts.size()) return false; - - for (UnitPart part: unitParts) - { - UnitTypes type = GetTypeFromUnit(part.Unit); - int exponent = part.Exponent; - if (Linq.FirstOrDefault(compoundParts, x -> x.Type.equals(type) && x.Exponent.equals(exponent), null) == null) - { - return false; - } - } - - return true; - } - - static ArrayList GetCompoundComparisonUnitParts(UnitInfo unitInfo, int type) - { - return - ( - type == 1 ? - new ArrayList(unitInfo.Parts) : - GetUnitPartsForAnyUnit(unitInfo) - ); - } - - static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system) - { - return GetBasicCompoundUnitParts(type, system, false); - } - - public static ArrayList GetBasicCompoundUnitParts(UnitTypes type, UnitSystems system, boolean onePartCompound) - { - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - return GetCompoundUnitParts - ( - HCCompounds.AllBasicCompounds.get(type).get(system), true, - type, system, onePartCompound - ); - } - - return new ArrayList(); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit) - { - return GetBasicCompoundUnitParts(unit, false); - } - - public static ArrayList GetBasicCompoundUnitParts(Units unit, boolean onePartCompound) - { - return GetCompoundUnitParts - ( - unit, true, UnitTypes.None, - UnitSystems.None, onePartCompound - ); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound) - { - return GetCompoundUnitParts(unit, basicCompound, UnitTypes.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type) - { - return GetCompoundUnitParts(unit, basicCompound, type, UnitSystems.None); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system) - { - return GetCompoundUnitParts(unit, basicCompound, type, system, false); - } - - static ArrayList GetCompoundUnitParts(Units unit, boolean basicCompound, UnitTypes type, UnitSystems system, boolean onePartCompound) - { - ArrayList unitParts = new ArrayList(); - - if (basicCompound) - { - if (type == UnitTypes.None) - { - type = GetTypeFromUnit(unit); - system = GetSystemFromUnit(unit); - } - - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - - } - if (HCCompounds.AllBasicCompounds.containsKey(type) && HCCompounds.AllBasicCompounds.get(type).containsKey(system)) - { - for (Compound compound: HCCompounds.AllCompounds.get(type)) - { - if (onePartCompound && compound.Parts.size() > 1) - { - //AllCompounds includes various versions for each compound. onePartCompound being true - //means that only 1-part compounds are relevant. - continue; - } - //When onePartCompound is false, the primary/most-expanded version is expected. - //In AllCompounds, this version is always located in the first position for the given type. - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basicUnit = HCCompounds.AllBasicUnits.get(compoundPart.Type).get(system); - - unitParts.add - ( - UnitPartInternal.NewUnitPart - ( - basicUnit.Unit, basicUnit.PrefixFactor, - compoundPart.Exponent - ) - ); - } - - return unitParts; - } - } - } - else if (HCCompounds.AllNonBasicCompounds.containsKey(unit)) - { - unitParts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unit))); - } - - return unitParts; - } - - static ArrayList GetUnitPartsForAnyUnit(UnitInfo unitInfo) - { - ArrayList outParts = new ArrayList(); - - for (UnitPart part: unitInfo.Parts) - { - //Under these specific conditions, GetTypeFromUnit is good enough on account of the fact that the - //exponent is irrelevant. - //For example: m3 wouldn't go through this part (type 1 match) and the exponent doesn't define litre. - //Note that these parts aren't actually correct in many cases, just compatible with the AllCompounds format. - UnitTypes type2 = GetTypeFromUnitPart(part, false, true); - if (HCCompounds.AllCompounds.containsKey(type2)) - { - ArrayList parts2 = GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(type2).get(0), - unitInfo.System, (int)Math.signum(part.Exponent) - ); - - outParts.addAll - ( - AddExponentInformationToParts2(parts2, part) - ); - } - else outParts.add(new UnitPart(part)); - - outParts = SimplifyCompoundComparisonUnitParts(outParts).Parts; - } - - return outParts; - } - - static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system) - { - return GetUnitPartsFromBasicCompound(compound, system, 1); - } - - public static ArrayList GetUnitPartsFromBasicCompound(Compound compound, UnitSystems system, int sign) - { - ArrayList outParts = new ArrayList(); - if (system == UnitSystems.None) system = UnitSystems.SI; - - for (CompoundPart compoundPart: compound.Parts) - { - BasicUnit basic = HCCompounds.AllBasicUnits.get(compoundPart.Type). - get(HCMain.AllBasicSystems.get(system)); - outParts.add - ( - UnitPartInternal.NewUnitPart - ( - basic.Unit, basic.PrefixFactor, - sign * compoundPart.Exponent - ) - ); - } - - return outParts; - } - - static ArrayList AddExponentInformationToParts2(ArrayList parts2, UnitPart part) - { - if (part.Exponent == 1) return parts2; - - //pint^2 converted into (ft3)^2 represents a descriptive example of the kind of situations - //which reach this point. That is, part.Exponent doesn't participate in the definition of - //the given unit/part. The definitory exponents are already stored in parts2. - - for (int i = 0; i < parts2.size(); i++) - { - parts2.get(i).Exponent *= part.Exponent; - } - - return parts2; - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts) - { - return SimplifyCompoundComparisonUnitParts(unitParts, false); - } - - public static UnitInfo SimplifyCompoundComparisonUnitParts(ArrayList unitParts, boolean checkPrefixes) - { - UnitInfo outInfo = null; - try - { - outInfo = new UnitInfo(1.0) - {{ - Parts = new ArrayList(unitParts); - }}; - - } - catch(Exception e) - { - //This part will never be reached because all the calculations are caught/managed (= no uncontrolled exceptions). - //The whole point of this try-catch is to comply with the Java compiler requirements without adding a throws declaration. - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - for (int i2 = i - 1; i2 >= 0; i2--) - { - UnitTypes type1 = GetTypeFromUnit(outInfo.Parts.get(i).Unit); - UnitTypes type2 = GetTypeFromUnit(outInfo.Parts.get(i2).Unit); - if (type1 == type2) - { - if (outInfo.Parts.get(i).Unit != outInfo.Parts.get(i2).Unit) - { - //This method is only called to perform basic unit matching; more specifically, finding - //the (dividable) compounds best matching the non-dividable ones. No direct conversions - //will be performed among the outputs of this function, that's why the exact units aren't - //that important. For example: when dealing with rood/rod, the only output which matters - //is the resulting type (i.e., length). It doesn't matter if it is rod or ft or other unit. - outInfo.Parts.get(i).Unit = outInfo.Parts.get(i2).Unit; - } - else if (checkPrefixes && (outInfo.Parts.get(i).Prefix.Factor != 1.0 || outInfo.Parts.get(i2).Prefix.Factor != 1.0)) - { - //Reaching here means that the returned information will be used in an intermediate conversion. - //In such a scenario, unit part prefixes might become error sources. - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i).Prefix.Factor, - outInfo.Parts.get(i).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i).Prefix = new Prefix(); - - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, Managed.RaiseToIntegerExponent - ( - outInfo.Parts.get(i2).Prefix.Factor, - outInfo.Parts.get(i2).Exponent - ), - Operations.Multiplication - ); - - outInfo.Parts.get(i2).Prefix = new Prefix(); - } - - outInfo.Parts.get(i).Exponent += outInfo.Parts.get(i2).Exponent; - - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - outInfo.Parts.remove(i2); - - if (outInfo.Parts.size() == 0 || i > outInfo.Parts.size() - 1) - { - i = outInfo.Parts.size(); - break; - } - } - } - } - - for (int i = outInfo.Parts.size() - 1; i >= 0; i--) - { - if (outInfo.Parts.get(i).Exponent == 0) - { - outInfo.Parts.remove(i); - } - } - - return outInfo; - } - - public static UnitSystems GetSystemFromUnitInfo(UnitInfo unitInfo) - { - UnitSystems outSystem = UnitSystems.None; - - //Neutral types are meant to avoid misunderstandings like s*ft being understood as SI. - ArrayList neutralSystems = new ArrayList(); - boolean allNeutral = true; - - for (UnitPart part: unitInfo.Parts) - { - Units partUnit = part.Unit; - - UnitTypes partType = GetTypeFromUnit(partUnit); - UnitSystems system2 = GetSystemFromUnit(partUnit); - - if (HCOther.NeutralTypes.contains(partType)) neutralSystems.add(system2); - else - { - allNeutral = false; - if (outSystem == UnitSystems.None) outSystem = system2; - else if (outSystem != system2) break; - } - } - - if (outSystem == UnitSystems.None && allNeutral && neutralSystems.size() > 0) - { - //When all the units are neutral, their defining system cannot be ignored. - outSystem = Linq.FirstOrDefault - ( - Linq.GroupByJustCountAndOrderByDescending - ( - neutralSystems, new Comparator() - { - public int compare(UnitSystems first, UnitSystems second) - { - return first.compareTo(second); - } - } - ), - UnitSystems.None - ); - } - - return - ( - outSystem != UnitSystems.None ? - outSystem : GetSystemFromUnit(unitInfo.Unit) - ); - } - - //Called before performing any operation. - public static ErrorTypes GetOperationError(UnitInfo unitInfo1, UnitInfo unitInfo2, Operations operation) - { - if (operation == Operations.None) return ErrorTypes.InvalidOperation; - if (operation == Operations.Division && unitInfo2.Value == 0.0) - { - return ErrorTypes.NumericError; - } - - for (UnitInfo info: new ArrayList() {{ add(unitInfo1); add(unitInfo2); }}) - { - if (info.Error.Type != ErrorTypes.None) - { - return info.Error.Type; - } - } - - return ErrorTypes.None; - } - - public static UnitInfo GetUnitParts(UnitInfo unitInfo) - { - if (HCUnits.AllNonDividableUnits.contains(unitInfo.Unit)) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - - return unitInfo; - } - - unitInfo = ExpandUnitParts(unitInfo); - if (unitInfo.Parts.size() > 1) - { - unitInfo = SimplifyUnitParts(unitInfo); - } - - return UpdateInitialPositions(unitInfo); - } - - public static UnitInfo ImproveUnitParts(UnitInfo unitInfo) - { - //GetUnitParts isn't just meant to get parts, but also to expand/simplify them. - //That's why calling this method is one of the first steps when improving/analysing - //a compound regardless of the fact that unit parts are already present. - return MethodsCommon.GetUnitParts(unitInfo); - } - - public static UnitInfo GetUnitFromParts(UnitInfo unitInfo) - { - unitInfo = GetIndividualUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetCompoundUnitFromParts(unitInfo) - ); - } - - static UnitInfo GetIndividualUnitFromParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 1 && unitInfo.Parts.get(0).Exponent == 1.0) - { - if (HCMain.AllUnitConversionFactors.containsKey(unitInfo.Parts.get(0).Unit)) - { - unitInfo.Unit = unitInfo.Parts.get(0).Unit; - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, unitInfo.Parts.get(0).Prefix.Factor, Operations.Multiplication - ); - unitInfo.Parts.get(0).Prefix = new Prefix(); - } - } - - return unitInfo; - } - - public static UnitInfo UpdateInitialPositions(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - int newPos = - ( - unitInfo.InitialPositions.size() > 0 ? Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() : 0 - ); - - //Some unit part modifications get a bit too messy and InitialPositions isn't always updated properly. - //This is a simple and reliable way to account for eventual problems on this front. - for (UnitPart part: unitInfo.Parts) - { - if (!unitInfo.InitialPositions.containsKey(part)) - { - newPos = newPos + 1; - unitInfo.InitialPositions.put(part, newPos); - } - } - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => unitInfo.InitialPositions.First(y => y.Key == x).Value - //) - int result = Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(first), null - ) - .getValue().compareTo - ( - Linq.FirstOrDefaultDict - ( - unitInfo.InitialPositions, x -> x.getKey().equals(second), null - ) - .getValue() - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenByDescending(x => x.Exponent) - new Integer(second.Exponent).compareTo(first.Exponent) - ); - } - } - ); - - return unitInfo; - } - - static UnitInfo SimplifyUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - //When having more than one part of the same type, a conversion (+ later removal) is performed. - //By default, the part with the higher index is kept. That's why it is better to reorder the parts - //such that the ones belonging to systems more likely to be preferred are kept. - - unitInfo.Parts = Linq.OrderBy - ( - unitInfo.Parts, new Comparator() - { - public int compare(UnitPart first, UnitPart second) - { - //Original C# code: - //unitInfo.Parts.OrderBy - //( - // x => GetUnitSystem(x.Unit) == UnitSystems.None - //) - int result = new Boolean(UnitP.GetUnitSystem(first.Unit) == UnitSystems.None).compareTo - ( - UnitP.GetUnitSystem(second.Unit) == UnitSystems.None - ); - - return - ( - result != 0 ? result ://Original C# code -> .ThenBy(x => AllMetricEnglish[GetUnitSystem(x.Unit)] == UnitSystems.Imperial) - new Boolean(HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(first.Unit)) == UnitSystems.Imperial).compareTo - ( - (HCMain.AllMetricEnglish.get(UnitP.GetUnitSystem(second.Unit)) == UnitSystems.Imperial) - ) - ); - } - } - ); - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - if (unitInfo.Parts.get(i).Unit == Units.None || unitInfo.Parts.get(i).Unit == Units.Unitless) - { - continue; - } - - //Bear in mind that this point can also be reached while extracting the parts of a known unit. - if (unitInfo.Unit == Units.None) - { - //Checking non-basic compounds is very quick (+ can avoid some of the subsequent analyses). - //Additionally, some of these compounds wouldn't be detected in case of performing a full - //simplification. For example: in Wh, all the time parts would be converted into hour or second - //and, consequently, recognised as other energy unit (joule or unnamed one). - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - if (unitInfo.Type != UnitTypes.None) - { - return unitInfo; - } - } - - for (int i2 = i - 1; i2 >= 0; i2--) - { - boolean remove = false; - if (unitInfo.Parts.get(i).Unit == unitInfo.Parts.get(i2).Unit) - { - remove = true; - } - else - { - UnitInfo tempInfo = Conversions.AdaptUnitParts(unitInfo, i, i2); - if (tempInfo != null) - { - remove = true; - unitInfo = tempInfo; - } - } - - if (remove) - { - unitInfo = SimplifyUnitPartsRemove(unitInfo, i, i2); - } - - if (unitInfo.Parts.size() == 0 || i > unitInfo.Parts.size() - 1) - { - i = unitInfo.Parts.size(); - break; - } - } - } - - if (unitInfo.Parts.size() == 0) unitInfo.Unit = Units.Unitless; - - return unitInfo; - } - - static UnitInfo SimplifyUnitPartsRemove(UnitInfo unitInfo, int i, int i2) - { - if (unitInfo.Parts.get(i).Prefix.Factor == unitInfo.Parts.get(i2).Prefix.Factor) - { - unitInfo.Parts.get(i).Exponent += unitInfo.Parts.get(i2).Exponent; - } - else unitInfo = UpdateDifferentPrefixParts(unitInfo, i, i2); - - if (unitInfo.Parts.get(i).Exponent == 0) - { - unitInfo = RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)); - } - - return RemoveUnitPart(unitInfo, unitInfo.Parts.get(i2)); - } - - static UnitInfo UpdateDifferentPrefixParts(UnitInfo unitInfo, int i, int i2) - { - //Example: m/cm is converted into 0.01 m/m where 0.01 isn't stored as a part but globally. - UnitInfo newInfo = GetNewPrefixUnitPart(unitInfo, i, i2); - newInfo = Managed.PerformManagedOperationUnits - ( - newInfo, unitInfo.Prefix.Factor, - Operations.Multiplication - ); - - unitInfo = Managed.PerformManagedOperationValues - ( - unitInfo, newInfo, Operations.Multiplication - ); - - unitInfo.Parts.get(i).Prefix = new Prefix(unitInfo.Parts.get(i).Prefix.PrefixUsage); - unitInfo.Parts.get(i).Exponent = unitInfo.Parts.get(i).Exponent + unitInfo.Parts.get(i2).Exponent; - - return unitInfo; - } - - static UnitInfo GetNewPrefixUnitPart(UnitInfo unitInfo, int i, int i2) - { - UnitInfo info1 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i).Prefix.Factor, - unitInfo.Parts.get(i).Exponent - ); - - UnitInfo info2 = Managed.RaiseToIntegerExponent - ( - unitInfo.Parts.get(i2).Prefix.Factor, - unitInfo.Parts.get(i2).Exponent - ); - - return Managed.PerformManagedOperationUnits(info1, info2, Operations.Multiplication); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart) - { - return UnitPartToUnitInfo(unitPart, 1.0); - } - - public static UnitInfo UnitPartToUnitInfo(UnitPart unitPart, double value) - { - Units unit = unitPart.Unit; - UnitInfo outUnitInfo = ExceptionInstantiation.NewUnitInfo(value, unit, unitPart.Prefix); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo); - - UnitTypes type = GetTypeFromUnitPart(unitPart); - - if (GetTypeFromUnit(unit) != type) - { - HashMap potentials = new HashMap(); - for (Map.Entry compoundUnit: Linq.WhereDict(HCMain.AllUnitTypes, x -> x.getValue().equals(type) && MethodsCommon.UnitIsNamedCompound(x.getKey())).entrySet()) - { - //AllUnitTypes.Where(x => x.Value == type && UnitIsNamedCompound(x.Key))) - Units unit2 = compoundUnit.getKey(); - - int count = 0; - while (count < 2) - { - count = count + 1; - ArrayList unitParts = GetCompoundUnitParts(unit2, count == 2); - if (unitParts.size() == 1) - { - potentials.put(unit2, unitParts.get(0)); - break; - } - } - } - - for (Map.Entry potential: potentials.entrySet()) - { - if (MethodsCommon.UnitPartsAreEquivalent(potential.getValue(), unitPart)) - { - outUnitInfo.Unit = potential.getKey(); - outUnitInfo = UpdateMainUnitVariables(outUnitInfo, true); - return outUnitInfo; - } - } - } - - return outUnitInfo; - } - - public static boolean UnitIsNamedCompound(Units unit) - { - return - ( - UnitIsNonBasicCompound(unit) ? true : - UnitIsBasicCompound(unit) - ); - } - - static boolean UnitIsBasicCompound(Units unit) - { - for (Map.Entry> item: HCCompounds.AllBasicCompounds.entrySet()) - { - if (item.getValue().containsValue(unit)) - { - return true; - } - } - - return false; - } - - static boolean UnitIsNonBasicCompound(Units unit) - { - return HCCompounds.AllNonBasicCompounds.containsKey(unit); - } - - static boolean UnitPartsAreEquivalent(UnitPart unitPart1, UnitPart unitPart2) - { - if (unitPart1.Unit == unitPart2.Unit && unitPart1.Prefix == unitPart2.Prefix) - { - if (Math.abs(unitPart1.Exponent) == Math.abs(unitPart2.Exponent)) - { - //Exponent sign isn't too relevant in quite a few matching UnitPart scenarios. - //For example: standalone kg and the one in L/kg. - return true; - } - } - - return false; - } - - static UnitInfo GetNonBasicCompoundUnitFromParts(UnitInfo unitInfo) - { - for (Map.Entry> compound: new HashMap>(HCCompounds.AllNonBasicCompounds).entrySet()) - { - if (HCCompounds.NonBasicCompoundsToSkip.contains(compound.getKey())) - { - continue; - } - - if (compound.getValue().size() == unitInfo.Parts.size()) - { - ArrayList targetParts = compound.getValue(); - if (UnitPartsMatchCompoundUnitParts(unitInfo, targetParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, compound.getKey()); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, targetParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, targetParts); - } - - return unitInfo; - } - } - } - - return unitInfo; - } - - static UnitInfo AdaptPrefixesToMatchBasicCompound(UnitInfo unitInfo, ArrayList basicUnitParts) - { - UnitInfo allPrefixes = ExceptionInstantiation.NewUnitInfo(1.0); - HashMap basicPrefixes = (HashMap) basicUnitParts.stream().collect - ( - Collectors.toMap(x -> x.Unit, x -> x.Prefix.Factor) - ); - - for (UnitPart part: unitInfo.Parts) - { - if (Linq.FirstOrDefault(basicUnitParts, x -> x.equals(part), null) == null) - { - UnitInfo prefixRem = Managed.PerformManagedOperationValues - ( - part.Prefix.Factor, basicPrefixes.get(part.Unit), Operations.Division - ); - - prefixRem = Managed.RaiseToIntegerExponent(prefixRem, part.Exponent); - - allPrefixes = Managed.PerformManagedOperationValues - ( - allPrefixes, prefixRem, Operations.Multiplication - ); - - part.Prefix = new Prefix(basicPrefixes.get(part.Unit)); - } - } - - if (allPrefixes.Value != 1.0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, allPrefixes, Operations.Multiplication - ); - } - - return unitInfo; - } - - static UnitInfo PopulateUnitRelatedInfo(UnitInfo unitInfo, Units unit) - { - unitInfo.Unit = unit; - - if (unitInfo.Unit != Units.None && unitInfo.Unit != Units.Unitless && !IsUnnamedUnit(unitInfo.Unit)) - { - unitInfo.Type = HCMain.AllUnitTypes.get(unitInfo.Unit); - unitInfo.System = HCMain.AllUnitSystems.get(unitInfo.Unit); - } - - return unitInfo; - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts) - { - return UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, false); - } - - static boolean UnitPartsMatchCompoundUnitParts(UnitInfo unitInfo, ArrayList basicUnitParts, boolean noPrefixes) - { - for (UnitPart basic: basicUnitParts) - { - if (noPrefixes) - { - if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.Unit.equals(basic.Unit) && x.Exponent.equals(basic.Exponent), null) == null) - { - return false; - } - } - else if (Linq.FirstOrDefault(unitInfo.Parts, x -> x.equals(basic), null) == null) - { - return false; - } - } - - return true; - } - - static UnitInfo ExpandUnitParts(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() == 0) unitInfo = GetPartsFromUnit(unitInfo); - - if (unitInfo.InitialPositions == null || unitInfo.InitialPositions.size() == 0) - { - unitInfo.InitialPositions = GetInitialPositions(unitInfo.Parts); - } - - for (int i = unitInfo.Parts.size() - 1; i >= 0; i--) - { - UnitInfo infoPart = ExceptionInstantiation.NewUnitInfo - ( - 0.0, unitInfo.Parts.get(i).Unit, - unitInfo.Parts.get(i).Prefix, false - ); - - if (IsDividable(infoPart)) - { - unitInfo = AddCompoundParts(unitInfo, infoPart, i); - } - } - - return unitInfo; - } - - static UnitInfo AddCompoundParts(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return - ( - HCCompounds.AllNonBasicCompounds.containsKey(partInfo.Unit) ? - ExpandNonBasicCompoundToUnitPart(unitInfo, partInfo, i) : - ExpandBasicCompoundToUnitPart(unitInfo, partInfo, i) - ); - } - - static UnitInfo ExpandBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - UnitTypes nonDividableType = - ( - HCUnits.AllNonDividableUnits.contains(unitInfo.Parts.get(i).Unit) ? - partInfo.Type : UnitTypes.None - ); - - for (int i2 = 0; i2 < HCCompounds.AllCompounds.get(partInfo.Type).size(); i2++) - { - Compound compound = HCCompounds.AllCompounds.get(partInfo.Type).get(i2); - if (HCCompounds.AllCompounds.get(partInfo.Type).get(i2).Parts.size() < 2) - { - //The whole point here is expanding. - continue; - } - - if (nonDividableType == UnitTypes.None || Linq.FirstOrDefault(compound.Parts, x -> x.Type.equals(nonDividableType), null) != null) - { - unitInfo = AddExpandedUnitPart - ( - unitInfo, i, GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(partInfo.Type).get(i2), - HCMain.AllBasicSystems.get(unitInfo.System) - ) - ); - break; - } - } - - return unitInfo; - } - - static UnitInfo AddExpandedUnitPart(UnitInfo unitInfo, int i, ArrayList compoundUnitParts) - { - //The prefix of the original unit is added to the first unit part. - boolean firstTime = true; - ArrayList newParts = new ArrayList(); - - for (UnitPart part: compoundUnitParts) - { - UnitInfo newPrefixInfo = ExceptionInstantiation.NewUnitInfo(Units.None, part.Prefix.Factor); - - if (firstTime && unitInfo.Parts.get(i).Prefix.Factor != 1.0) - { - //Finding the most adequate new prefix isn't required at this point. - newPrefixInfo = Managed.PerformManagedOperationValues - ( - unitInfo.Parts.get(i).Prefix.Factor, part.Prefix.Factor, - Operations.Multiplication - ); - - if (newPrefixInfo.Value != 1 || newPrefixInfo.BaseTenExponent != 0) - { - unitInfo = Managed.PerformManagedOperationUnits - ( - unitInfo, newPrefixInfo, Operations.Multiplication - ); - } - } - - newParts.add - ( - UnitPartInternal.NewUnitPart - ( - part.Unit, newPrefixInfo.Prefix.Factor, - part.Exponent * unitInfo.Parts.get(i).Exponent - ) - ); - - firstTime = false; - } - - return AddNewUnitParts(unitInfo, newParts, i); - } - - public static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts) - { - return AddNewUnitParts(unitInfo, newParts, -1); - } - - static UnitInfo AddNewUnitParts(UnitInfo unitInfo, ArrayList newParts, int i) - { - if (newParts.size() < 1) return unitInfo; - - int i2 = i; - if (i2 == -1) - { - i2 = - ( - unitInfo.InitialPositions.size() == 0 ? 0 : Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - - for (UnitPart part: newParts) - { - unitInfo.Parts.add(part); - if (!unitInfo.InitialPositions.containsKey(part)) - { - unitInfo.InitialPositions.put(part, i2); - } - } - - return - ( - i == -1 ? unitInfo : //i == -1 means that old parts aren't being replaced. - RemoveUnitPart(unitInfo, unitInfo.Parts.get(i)) - ); - } - - static UnitInfo RemoveUnitPart(UnitInfo unitInfo, UnitPart part) - { - unitInfo.InitialPositions.remove(part); - unitInfo.Parts.remove(part); - - return unitInfo; - } - - static UnitInfo ExpandNonBasicCompoundToUnitPart(UnitInfo unitInfo, UnitInfo partInfo, int i) - { - return AddExpandedUnitPart - ( - unitInfo, i, - new ArrayList(HCCompounds.AllNonBasicCompounds.get(partInfo.Unit)) - ); - } - - public static UnitInfo GetPartsFromUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.None || unitInfo.Unit == Units.Unitless || IsUnnamedUnit(unitInfo.Unit)) - { - return unitInfo; - } - - unitInfo = GetPartsFromUnitCompound(unitInfo); - - if (unitInfo.Parts.size() < 1) - { - unitInfo.Parts = new ArrayList(); - unitInfo.Parts.add(new UnitPart(unitInfo.Unit, 1)); - } - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompound(UnitInfo unitInfo) - { - //Always better to start compound analyses with the more-to-the-point non-basic ones. - unitInfo = GetPartsFromUnitCompoundNonBasic(ExceptionInstantiation.NewUnitInfo(unitInfo)); - if (unitInfo.Parts.size() > 0) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - if (unitInfo.System == UnitSystems.None) - { - unitInfo.System = GetSystemFromUnit(unitInfo.Unit); - } - - return - ( - GetBasicCompoundUnitInfo(unitInfo).Unit == unitInfo.Unit ? - GetPartsFromUnitCompoundBasic(unitInfo) : - unitInfo - ); - } - - static UnitInfo GetPartsFromUnitCompoundBasic(UnitInfo unitInfo) - { - if (unitInfo.System == UnitSystems.None || !HCCompounds.AllCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Parts.addAll - ( - GetUnitPartsFromBasicCompound - ( - HCCompounds.AllCompounds.get(unitInfo.Type).get(0), unitInfo.System - ) - ); - - return unitInfo; - } - - static UnitInfo GetPartsFromUnitCompoundNonBasic(UnitInfo unitInfo) - { - if (HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit)) - { - unitInfo.Parts.addAll(new ArrayList(HCCompounds.AllNonBasicCompounds.get(unitInfo.Unit))); - } - - return unitInfo; - } - - public static UnitInfo GetCompoundUnitFromParts(UnitInfo unitInfo) - { - //Better starting with the quicker non-basic-compound check. - unitInfo = GetNonBasicCompoundUnitFromParts(unitInfo); - - return - ( - unitInfo.Unit != Units.None ? unitInfo : - GetBasicCompoundUnitInfo(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Parts.size() < 1) return unitInfo; - - if (unitInfo.Type == UnitTypes.None) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - } - - return - ( - unitInfo.Type == UnitTypes.None ? unitInfo : - GetBasicCompoundUnit(unitInfo) - ); - } - - static UnitInfo GetBasicCompoundUnit(UnitInfo unitInfo) - { - if (!HCCompounds.AllBasicCompounds.containsKey(unitInfo.Type)) - { - return unitInfo; - } - - unitInfo.Unit = HCMain.DefaultUnnamedUnits.get(unitInfo.System); - - UnitSystems system2 = unitInfo.System; - if (system2 == UnitSystems.None) - { - system2 = UnitSystems.SI; - } - - Units basicCompound = - ( - HCCompounds.AllBasicCompounds.get(unitInfo.Type).containsKey(system2) ? - HCCompounds.AllBasicCompounds.get(unitInfo.Type).get(system2) : - Units.None - ); - - if (basicCompound == Units.None) return unitInfo; - - UnitSystems basicSystem = HCMain.AllBasicSystems.get(system2); - ArrayList basicUnitParts = GetBasicCompoundUnitParts(unitInfo.Type, basicSystem); - if (basicUnitParts.size() != unitInfo.Parts.size()) return unitInfo; - - if (UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts, true)) - { - unitInfo = PopulateUnitRelatedInfo(unitInfo, basicCompound); - if (!UnitPartsMatchCompoundUnitParts(unitInfo, basicUnitParts)) - { - //Some prefixes differ from the basic configuration. - unitInfo = AdaptPrefixesToMatchBasicCompound(unitInfo, basicUnitParts); - } - } - - return unitInfo; - } - - static boolean IsDividable(UnitInfo unitInfo) - { - unitInfo.Type = GetTypeFromUnitInfo(unitInfo); - - return - ( - !HCUnits.AllNonDividableUnits.contains(unitInfo.Unit) && - ( - HCCompounds.AllCompounds.containsKey(unitInfo.Type) || - HCCompounds.AllNonBasicCompounds.containsKey(unitInfo.Unit) - ) - ); - } - - public static boolean IsCompoundDescriptive(char bit) - { - return IsCompoundDescriptive(bit, false); - } - - public static boolean IsCompoundDescriptive(char bit, boolean ignoreNumbers) - { - return - ( - (!ignoreNumbers && Character.isDigit(bit)) || bit == '-' || - OperationsOther.OperationSymbols.get(Operations.Multiplication).contains(bit) || - OperationsOther.OperationSymbols.get(Operations.Division).contains(bit) - ); - } - - public static boolean PrefixCanBeUsedWithUnitBasicCheck(UnitInfo unitInfo, PrefixTypes prefixType) - { - if (unitInfo.Prefix.PrefixUsage == PrefixUsageTypes.AllUnits) return true; - - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.AllOtherSIPrefixUnits.contains(unitInfo.Unit)) return true; - - UnitSystems system = - ( - unitInfo.System == UnitSystems.None ? - GetSystemFromUnitInfo(unitInfo) : - unitInfo.System - ); - - return (system == UnitSystems.SI || system == UnitSystems.CGS); - } - else if (prefixType == PrefixTypes.Binary) - { - UnitTypes type = - ( - unitInfo.Type == UnitTypes.None ? - GetTypeFromUnitInfo(unitInfo) : - unitInfo.Type - ); - return HCPrefixes.AllBinaryPrefixTypes.contains(type); - } - - return false; - } - - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType) - { - return GetBestPrefixForTarget - ( - unitInfo, targetExponent, prefixType, false - ); - } - - //This method assumes a normalised UnitInfo variable (i.e., without prefixes). - static UnitInfo GetBestPrefixForTarget(UnitInfo unitInfo, int targetExponent, PrefixTypes prefixType, boolean modifyBaseTenExponent) - { - if (targetExponent == 0 || prefixType == PrefixTypes.None) return unitInfo; - - if (targetExponent > 24) targetExponent = 24; - else if(targetExponent < -24) targetExponent = -24; - - UnitInfo targetInfo = Managed.RaiseToIntegerExponent(10, targetExponent); - - for (double prefixFactor: GetAllPrefixFactors(targetExponent, prefixType)) - { - if ((targetExponent > 0 && targetInfo.Value >= prefixFactor) || (targetExponent < 0 && targetInfo.Value <= prefixFactor)) - { - unitInfo = IncludeRemainingTargetPrefix - ( - unitInfo, targetInfo, ExceptionInstantiation.NewUnitInfo(prefixFactor) - ); - System.out.println(prefixFactor); - unitInfo.Prefix = new Prefix(prefixFactor, unitInfo.Prefix.PrefixUsage); - break; - } - } - //System.out.println(unitInfo.Value + " " + unitInfo.BaseTenExponent + " " + unitInfo.Prefix.Factor); - return - ( - modifyBaseTenExponent ? - Managed.VaryBaseTenExponent(unitInfo, -targetExponent) : - unitInfo - ); - } - - static UnitInfo IncludeRemainingTargetPrefix(UnitInfo unitInfo, UnitInfo expectedTarget, UnitInfo actualTarget) - { - UnitInfo remInfo = Managed.NormaliseUnitInfo - ( - Managed.PerformManagedOperationValues - ( - expectedTarget, actualTarget, Operations.Division - ) - ); - - return Managed.PerformManagedOperationValues(unitInfo, remInfo, Operations.Multiplication); - } - - static ArrayList GetAllPrefixFactors(int targetExponent, PrefixTypes prefixType) - { - ArrayList allPrefixes = null; - - InitialiseBigSmallPrefixValues(prefixType); - if (prefixType == PrefixTypes.SI) - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigSIPrefixValues : HCPrefixes.SmallSIPrefixValues - ); - } - else - { - allPrefixes = - ( - targetExponent > 0 ? HCPrefixes.BigBinaryPrefixValues : HCPrefixes.SmallBinaryPrefixValues - ); - } - - return allPrefixes; - } - - static void InitialiseBigSmallPrefixValues(PrefixTypes prefixType) - { - if (prefixType == PrefixTypes.SI) - { - if (HCPrefixes.BigSIPrefixValues == null) - { - HCPrefixes.BigSIPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallSIPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllSIPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - else if(prefixType == PrefixTypes.Binary) - { - if (HCPrefixes.BigBinaryPrefixValues == null) - { - HCPrefixes.BigBinaryPrefixValues = Linq.OrderByDescending - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == 1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - if (HCPrefixes.SmallSIPrefixValues == null) - { - HCPrefixes.SmallBinaryPrefixValues = Linq.OrderBy - ( - Linq.SelectDict - ( - Linq.WhereDict - ( - HCPrefixes.AllBinaryPrefixes, x -> x.getValue().compareTo(1.0) == -1 - ), - x -> x.getValue() - ), - new Comparator() - { - public int compare(Double first, Double second) - { - return first.compareTo(second); - } - } - ); - } - } - } - - //Called before starting unit conversions triggered by public methods. - public static ErrorTypes PrelimaryErrorCheckConversion(UnitP original, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (original == null) - { - outError = ErrorTypes.InvalidUnit; - } - else if (original.Error.Type != ErrorTypes.None) - { - outError = original.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - - return outError; - } - - public static UnitInfo InverseUnit(UnitInfo unitInfo) - { - if (unitInfo.Unit == Units.Unitless || unitInfo.Unit == Units.None || unitInfo.Parts.size() == 0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - for (int i = 0; i < outInfo.Parts.size(); i++) - { - outInfo.Parts.set - ( - i, UnitPartInternal.NewUnitPart - ( - outInfo.Parts.get(i).Unit, outInfo.Parts.get(i).Prefix.Factor, - -1 * outInfo.Parts.get(i).Exponent - ) - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fd/5080fc70984a00171930ee4d171ed0de b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fd/5080fc70984a00171930ee4d171ed0de deleted file mode 100644 index 7cb3c10..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fd/5080fc70984a00171930ee4d171ed0de +++ /dev/null @@ -1,567 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - //After being normalised, the operands might require further modifications. - ArrayList normalised = GetOperandsAddition(firstInfo, secondInfo, operation); - - return PerformManagedOperationNormalisedValues - ( - firstInfo, normalised, operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fe/60a79486b34a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fe/60a79486b34a00171059ebc16969059f deleted file mode 100644 index 391f7f7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fe/60a79486b34a00171059ebc16969059f +++ /dev/null @@ -1,565 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Managed -{ - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, double second, Operations operation) - { - return PerformManagedOperationUnits - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(second), operation - ); - } - - public static UnitInfo PerformManagedOperationUnits(double first, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationUnits - ( - ExceptionInstantiation.NewUnitInfo(first), secondInfo, operation - ); - } - - //This method should always be used when dealing with random UnitInfo variables because it accounts for all the - //possible scenarios. On the other hand, with simple operations (e.g., random UnitInfo & numeric type) it might - //be better to use PerformManagedOperationValues. - public static UnitInfo PerformManagedOperationUnits(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ErrorTypes errorType = MethodsCommon.GetOperationError - ( - firstInfo, secondInfo, operation - ); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(firstInfo, errorType); - } - - return - ( - operation == Operations.Addition || operation == Operations.Subtraction ? - PerformManagedOperationAddition(firstInfo, secondInfo, operation) : - PerformManagedOperationMultiplication(firstInfo, secondInfo, operation) - ); - } - - static UnitInfo PerformManagedOperationAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - //After being normalised, the operands might require further modifications. - firstInfo, GetOperandsAddition(firstInfo, secondInfo, operation), operation - ); - } - - static ArrayList GetOperandsAddition(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - ArrayList operands2 = new ArrayList() - {{ - add(ExceptionInstantiation.NewUnitInfo(firstInfo)); add(ExceptionInstantiation.NewUnitInfo(secondInfo)); - }}; - - if (operands2.get(0).BaseTenExponent != operands2.get(1).BaseTenExponent || operands2.get(0).Prefix.Factor != operands2.get(1).Prefix.Factor) - { - //The addition/subtraction might not be performed right away even with normalised values. - //For example: 5 and 6 from 5*10^2 and 6*10^7 cannot be added right away. - - ArrayList operandArgs = new ArrayList(); - operandArgs.add(NormaliseUnitInfo(operands2.get(0))); - operandArgs.add(NormaliseUnitInfo(operands2.get(1))); - - operands2 = AdaptNormalisedValuesForAddition - ( - operandArgs, operation - ); - } - - return operands2; - } - - static ArrayList AdaptNormalisedValuesForAddition(ArrayList unitInfos2, Operations operation) - { - if (unitInfos2.get(0).BaseTenExponent == unitInfos2.get(1).BaseTenExponent) - { - //Having the same BaseTenExponent values means that the given operation can be performed right away. - return unitInfos2; - } - - int[] bigSmallI = - ( - unitInfos2.get(0).BaseTenExponent > unitInfos2.get(1).BaseTenExponent ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - UnitInfo big2 = AdaptBiggerAdditionOperand(unitInfos2, bigSmallI, operation); - if (big2.Error.Type != ErrorTypes.None) - { - return TooBigGapAddition(unitInfos2, bigSmallI, operation); - } - - unitInfos2.set - ( - bigSmallI[0], ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(bigSmallI[0]), big2.Value, unitInfos2.get(bigSmallI[1]).BaseTenExponent - ) - ); - - return unitInfos2; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum double range, there - //is no need to perform any operation (i.e., no change will be observed because of being outside - //the maximum supported precision). This method takes care of these cases and returns the expected - //output (i.e., biggest value). - static ArrayList TooBigGapAddition(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - ArrayList outInfos = new ArrayList() - {{ - //First operand (i.e., one whose information defines the operation) together with the - //numeric information (i.e., just Value and BaseTenExponent because both are normalised) - //which is associated with the biggest one. - add - ( - ExceptionInstantiation.NewUnitInfo - ( - unitInfos2.get(0), unitInfos2.get(bigSmallI[0]).Value, - unitInfos2.get(bigSmallI[0]).BaseTenExponent - ) - ); - }}; - - if (operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outInfos.get(0).Value = -1.0 * outInfos.get(0).Value; - } - - if (outInfos.get(0).Unit == Units.Unitless) - { - outInfos.get(0).Unit = unitInfos2.get(bigSmallI[1]).Unit; - } - - return outInfos; - } - - static UnitInfo AdaptBiggerAdditionOperand(ArrayList unitInfos2, int[] bigSmallI, Operations operation) - { - int gapExponent = unitInfos2.get(bigSmallI[0]).BaseTenExponent - unitInfos2.get(bigSmallI[1]).BaseTenExponent; - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum double value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - - //PerformManagedOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - UnitInfo big2 = PerformManagedOperationValues - ( - RaiseToIntegerExponent(10.0, gapExponent), unitInfos2.get(bigSmallI[0]).Value, - Operations.Multiplication - ); - - boolean isWrong = - ( - big2.Error.Type != ErrorTypes.None || big2.BaseTenExponent != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. In fact, with properly normalised variables, - //triggering an error would be plainly impossible. - AreAdditionFinalValuesWrong - ( - unitInfos2.get(0).Value, unitInfos2.get(1).Value, operation - ) - ); - - - UnitInfo output = null; - - if (isWrong) - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(0), ErrorTypes.InvalidOperation); - } - else - { - output = ExceptionInstantiation.NewUnitInfo(unitInfos2.get(bigSmallI[0]), big2.Value); - } - - return output; - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, Operations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == Operations.Addition ? 1 : -1 - ); - } - catch (Exception e) { isWrong = true; } - - return isWrong; - } - - static UnitInfo PerformManagedOperationMultiplication(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - return PerformManagedOperationNormalisedValues - ( - firstInfo, new ArrayList() - {{ - add(NormaliseUnitInfo(firstInfo)); - add(NormaliseUnitInfo(secondInfo)); - }}, - operation - ); - } - - public static UnitInfo RaiseToIntegerExponent(double baseValue, int exponent) - { - return RaiseToIntegerExponent(ExceptionInstantiation.NewUnitInfo(baseValue), exponent); - } - - public static UnitInfo RaiseToIntegerExponent(UnitInfo baseInfo, int exponent) - { - if (exponent <= 1 && exponent >= 0) - { - baseInfo.Value = (exponent == 0 ? 1.0 : baseInfo.Value); - return baseInfo; - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(baseInfo); - - for (int i = 1; i < Math.abs(exponent); i++) - { - outInfo = PerformManagedOperationValues - ( - outInfo, baseInfo, Operations.Multiplication - ); - if (outInfo.Error.Type != ErrorTypes.None) return outInfo; - } - - return - ( - exponent < 0 ? - PerformManagedOperationValues(ExceptionInstantiation.NewUnitInfo(1.0), outInfo, Operations.Division) : - outInfo - ); - } - - static UnitInfo PerformManagedOperationNormalisedValues(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - return - ( - normalisedInfos.size() == 1 ? - //There is just one operand when the difference between both of them is too big. - normalisedInfos.get(0) : - PerformManagedOperationTwoOperands(outInfo, normalisedInfos, operation) - ); - } - - static UnitInfo PerformManagedOperationTwoOperands(UnitInfo outInfo, ArrayList normalisedInfos, Operations operation) - { - UnitInfo outInfoNormalised = PerformManagedOperationValues - ( - normalisedInfos.get(0), normalisedInfos.get(1), operation - ); - - if (outInfo.Error.Type != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.NumericError); - } - - outInfo.BaseTenExponent = outInfoNormalised.BaseTenExponent; - outInfo.Value = outInfoNormalised.Value; - //Normalised means no prefixes. - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - - return outInfo; - } - - public static UnitInfo PerformManagedOperationValues(double firstValue, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - ExceptionInstantiation.NewUnitInfo(firstValue), ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, double secondValue, Operations operation) - { - return PerformManagedOperationValues - ( - firstInfo, ExceptionInstantiation.NewUnitInfo(secondValue), operation - ); - } - - //This method might be used to perform full operations (not just being the last calculation step) instead - //of the default one (PerformManagedOperationUnits) for simple cases. That is: ones not dealing with the - //complex numeric reality (Value, Prefix and BaseTenExponent) which makes a pre-analysis required. - //Note that, unlikely what happens with PerformMangedOperationUnits, the outputs of this method aren't - //normalised (= primarily stored under Value), what is useful in certain contexts. - //NOTE: this function assumes that both inputs are normalised, what means that no prefix information is expected. - //It might also be used with non-normalised inputs, but their prefix information would be plainly ignored. - public static UnitInfo PerformManagedOperationValues(UnitInfo firstInfo, UnitInfo secondInfo, Operations operation) - { - if (firstInfo.Value == 0.0 || secondInfo.Value == 0.0) - { - if (operation == Operations.Multiplication || operation == Operations.Division) - { - //Dividing by zero scenarios are taken into account somewhere else. - return ExceptionInstantiation.NewUnitInfo(firstInfo, 0.0); - } - } - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo firstInfo0 = ExceptionInstantiation.NewUnitInfo(firstInfo); - UnitInfo secondInfo0 = ExceptionInstantiation.NewUnitInfo(secondInfo); - - boolean isWrong = false; - try - { - if (operation == Operations.Addition) - { - outInfo.Value += secondInfo0.Value; - } - else if (operation == Operations.Subtraction) - { - outInfo.Value -= secondInfo.Value; - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - if (VaryBaseTenExponent(outInfo, secondInfo0.BaseTenExponent, operation == Operations.Division).Error.Type != ErrorTypes.None) - { - return new UnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - if (operation == Operations.Multiplication) - { - outInfo.Value *= secondInfo.Value; - outInfo.BaseTenExponent += secondInfo.BaseTenExponent; - } - else if (operation == Operations.Division) - { - if (secondInfo.Value == 0.0) - { - UnitInfo output = new UnitInfo(outInfo); - output.Error = new ErrorInfo(ErrorTypes.NumericError); - return output; - } - outInfo.Value /= secondInfo.Value; - outInfo.BaseTenExponent -= secondInfo.BaseTenExponent; - } - } - } - catch (Exception e) { isWrong = true; } - - return - ( - //An error might not be triggered despite of dealing with numbers outside double precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can output 0.0 without triggering an error. - isWrong || ((operation == Operations.Multiplication || operation == Operations.Division) && outInfo.Value == 0.0) ? - OperationValuesManageError(firstInfo0, secondInfo0, operation) : outInfo - ); - } - - static UnitInfo OperationValuesManageError(UnitInfo outInfo, UnitInfo secondInfo, Operations operation) - { - if (operation != Operations.Multiplication && operation != Operations.Division) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return ExceptionInstantiation.NewUnitInfo(outInfo, ErrorTypes.InvalidOperation); - } - - UnitInfo secondInfo2 = ConvertValueToBaseTen(secondInfo.Value); - outInfo = VaryBaseTenExponent(outInfo, secondInfo2.BaseTenExponent, operation == Operations.Division); - if (Math.abs(secondInfo2.Value) == 1.0 || outInfo.Error.Type != ErrorTypes.None) return outInfo; - - try - { - outInfo = PerformManagedOperationUnits - ( - outInfo, secondInfo2.Value, operation - ); - } - catch(Exception e) - { - //Very unlikely scenario on account of the fact that Math.abs(secondInfo2.Value) - //lies within the 0.1-10.0 range. - UnitInfo arg1 = ExceptionInstantiation.NewUnitInfo(outInfo); - arg1.Value = secondInfo2.Value; - arg1.BaseTenExponent = 0; - - UnitInfo arg2 = ExceptionInstantiation.NewUnitInfo(); - arg2.Value = outInfo.Value; - arg2.BaseTenExponent = outInfo.BaseTenExponent; - - outInfo = OperationValuesManageError(arg1, arg2, operation); - } - - return outInfo; - } - - static UnitInfo ConvertValueToBaseTen(double value) - { - value = Math.abs(value); - return FromValueToBaseTenExponent - ( - ExceptionInstantiation.NewUnitInfo(value), Math.abs(value), false - ); - } - - public static UnitInfo ConvertBaseTenToValue(UnitInfo unitInfo) - { - if (unitInfo.BaseTenExponent == 0) return unitInfo; - - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - boolean decrease = unitInfo.BaseTenExponent > 0; - int sign = (int)Math.signum(outInfo.Value); - double absValue = Math.abs(outInfo.Value); - - while (outInfo.BaseTenExponent != 0.0) - { - if (decrease) - { - if (absValue >= OperationsOther.MaxValue / 10.0) break; - absValue *= 10.0; - outInfo.BaseTenExponent -= 1; - } - else - { - if (absValue <= OperationsOther.MinValue * 10.0) break; - absValue /= 10.0; - outInfo.BaseTenExponent += 1; - } - } - - outInfo.Value = sign * absValue; - - return outInfo; - } - - public static UnitInfo NormaliseUnitInfo(UnitInfo unitInfo) - { - if (unitInfo.Value == 0 && unitInfo.Prefix.Factor == 1.0) - { - return unitInfo; - } - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(unitInfo); - - if (outInfo.Prefix.Factor != 1) - { - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Prefix.Factor, true - ); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - } - if (outInfo.Value == 0.0) return outInfo; - - outInfo = FromValueToBaseTenExponent - ( - outInfo, outInfo.Value, false - ); - - return outInfo; - } - - static UnitInfo FromValueToBaseTenExponent(UnitInfo outInfo, double value, boolean isPrefix) - { - if (value == 0.0) return outInfo; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - if (!isPrefix) - { - outInfo.Value = outInfo.Value / valueAbs; - } - - while (valueAbs != 1.0) - { - if ((valueAbs < 10.0 && valueAbs > 1.0) || (valueAbs > 0.1 && valueAbs < 1.0)) - { - if (!isPrefix) outInfo.Value = value; - else - { - outInfo = PerformManagedOperationValues - ( - outInfo, value, Operations.Multiplication - ); - } - - return outInfo; - } - - if (decrease) - { - value /= 10.0; - outInfo.BaseTenExponent += 1; - } - else - { - value *= 10.0; - outInfo.BaseTenExponent -= 1; - } - - valueAbs = Math.abs(value); - } - - return outInfo; - } - - - public static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease) - { - return VaryBaseTenExponent(info, baseTenIncrease, false); - } - - //Method used to vary BaseTenExponent without provoking unhandled exceptions (i.e., bigger than Integer.MAX_VALUE). - static UnitInfo VaryBaseTenExponent(UnitInfo info, int baseTenIncrease, boolean isDivision) - { - long val1 = info.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.abs(Integer.MAIN_VALUE)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - UnitInfo outInfo = null; - - if ((val2 > 0 && val1 > Integer.MAX_VALUE - val2) || (val2 < 0 && val1 < Integer.MIN_VALUE - val2)) - { - outInfo = ExceptionInstantiation.NewUnitInfo(info, ErrorTypes.NumericError); - } - else - { - outInfo = ExceptionInstantiation.NewUnitInfo(info); - outInfo.BaseTenExponent = (int)(val1 + val2); - } - - return outInfo; - } -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fe/a051d8c4b04a00171059ebc16969059f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fe/a051d8c4b04a00171059ebc16969059f deleted file mode 100644 index cd96448..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fe/a051d8c4b04a00171059ebc16969059f +++ /dev/null @@ -1,1053 +0,0 @@ -package InternalUnitParser.Operations; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Hardcoding.*; -import InternalUnitParser.Methods.*; -import UnitParser.*; -import UnitParser.UnitP.*; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -public class Conversions -{ - //List of types whose conversion requires more than just applying a conversion factor. - @SuppressWarnings("serial") - static ArrayList SpecialConversionTypes = new ArrayList() - {{ - add(UnitTypes.Temperature); - }}; - - public static UnitInfo AdaptUnitParts(UnitInfo unitInfo, int i, int i2) - { - ArrayList parts2 = GetUnitPartsConversion - ( - new UnitPart(unitInfo.Parts.get(i)), new UnitPart(unitInfo.Parts.get(i2)) - ); - if (parts2 == null) return null; - - UnitInfo tempInfo = ConvertUnitPartToTarget - ( - ExceptionInstantiation.NewUnitInfo(1.0), new UnitPart(parts2.get(0)), - new UnitPart(parts2.get(1)) - ); - - //Firstly, note that GetUnitPartsConversion might have affected the exponent. For example: in m4/L2, - //both exponents have to be modified to reach the convertible m3/L. Secondly, bear in mind that - //parts2 exponents are always positive. - - int sign = unitInfo.Parts.get(i).Exponent / Math.abs(unitInfo.Parts.get(i).Exponent); - int exponent = sign * unitInfo.Parts.get(i).Exponent / parts2.get(0).Exponent; - int outExponent = exponent; - if (exponent != 1.0) - { - tempInfo = Managed.RaiseToIntegerExponent(tempInfo, exponent); - } - - if (Math.abs(unitInfo.Parts.get(i).Exponent) > Math.abs(parts2.get(0).Exponent * exponent)) - { - exponent = sign * unitInfo.Parts.get(i).Exponent - parts2.get(0).Exponent * exponent; - if (exponent > 0) - { - //Accounting for cases like m4 converted to litre where 1 metre is left uncompensated. - UnitPart newPart = UnitPartInternal.NewUnitPart - ( - parts2.get(0).Unit, parts2.get(0).Prefix.Factor, sign * exponent - ); - unitInfo.Parts.add(newPart); - - if (!unitInfo.InitialPositions.containsKey(newPart)) - { - unitInfo.InitialPositions.put - ( - newPart, Linq.Max - ( - unitInfo.InitialPositions, new Comparator>() - { - public int compare(Map.Entry first, Map.Entry second) - { - return first.getValue().compareTo(second.getValue()); - } - } - ) - .getValue() + 1 - ); - } - } - } - - if (sign == -1) - { - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division); - } - outExponent = sign * outExponent; - - unitInfo = Managed.PerformManagedOperationUnits(unitInfo, tempInfo, Operations.Multiplication); - unitInfo.Parts.get(i).Unit = parts2.get(1).Unit; - //outExponent indicates the number of times which the target exponent is - //repeated to match the original unit. For example: in L to m3, the final - //unit is m and outExponent is 1 (= the original unit contains 1 target - //unit/exponent), but the output exponent should be 3 (1 * target exponent). - unitInfo.Parts.get(i).Exponent = outExponent * parts2.get(1).Exponent; - - return unitInfo; - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart) - { - return ConvertUnitPartToTarget(outInfo, originalPart, targetPart, true); - } - - static UnitInfo ConvertUnitPartToTarget(UnitInfo outInfo, UnitPart originalPart, UnitPart targetPart, boolean isInternal) - { - ErrorTypes errorType = GetUnitPartConversionError(originalPart, targetPart); - if (errorType != ErrorTypes.None) - { - outInfo.Error = ExceptionInstantiation.NewErrorInfo(errorType); - return outInfo; - } - - UnitPart originalPart2 = new UnitPart(originalPart); - UnitPart targetPart2 = new UnitPart(targetPart); - - int exponent2 = 1; - if (originalPart2.Exponent == targetPart2.Exponent) - { - if (!isInternal) - { - //In the internal calculations, exponents might be relevant or not when performing - //a unit part conversion; this issue is being managed by the code calling this function. - //With conversions delivered to the user, exponents have to be brought into account. - //NOT: isInternal isn't passed to PerformConversion because the associated modifications - //only make sense for the main prefix (not what this is about). - exponent2 = Math.abs(targetPart2.Exponent); - } - //In this situation, exponents don't need to be considered and it is better ignoring them during - //the conversion to avoid problems. - //For example: the part m2 has associated a specific unit (SquareMetre), but it might be converted - //into units which don't have one, like ft2. - originalPart2.Exponent = 1; - targetPart2.Exponent = 1; - } - //Different exponents cannot be removed. For example: conversion between litre and m3, where the exponent - //does define the unit. - - UnitInfo info2 = PerformConversion - ( - AdaptPartToConversion(originalPart2, originalPart.Exponent), - AdaptPartToConversion(targetPart2, targetPart.Exponent), true, - //The original part being in the denominator means that the output value has to be inverted. - //Note that this value is always expected to modify the main value (= in the numerator). - //This is the only conversion where such a scenario is being considered; but the information - //is passed to PerformConversion anyway to ensure the highest accuracy. Even the decimal type - //can output noticeable differences in cases like 1/(val1/val2) vs. val2/val1. - originalPart.Exponent / Math.abs(originalPart.Exponent) == -1 - ); - - return - ( - info2.Error.Type != ErrorTypes.None ? info2 : - Managed.PerformManagedOperationUnits - ( - outInfo, - ( - exponent2 == 1 ? info2 : - Managed.RaiseToIntegerExponent(info2, exponent2) - ), - Operations.Multiplication - ) - ); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo) - { - return PerformConversion(originalInfo, targetInfo, true, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion(originalInfo, targetInfo, isInternal, false); - } - - static UnitInfo PerformConversion(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal, boolean inverseOutputs) - { - ErrorTypes errorType = GetConversionError(originalInfo, targetInfo); - if (errorType != ErrorTypes.None) - { - return ExceptionInstantiation.NewUnitInfo(originalInfo, errorType); - } - - UnitInfo targetInfo2 = NormaliseTargetUnit(targetInfo, isInternal); - UnitInfo outInfo = AccountForTargetUnitPrefixes(originalInfo, targetInfo2); - - boolean convertIt = - ( - outInfo.Unit != targetInfo2.Unit || - ( - MethodsCommon.IsUnnamedUnit(originalInfo.Unit) && - MethodsCommon.IsUnnamedUnit(targetInfo.Unit) - ) - ); - - if (convertIt) - { - UnitInfo tempInfo = - ( - UnitsCanBeConvertedDirectly(outInfo, targetInfo2) ? - ConvertUnitValue(outInfo, targetInfo2, inverseOutputs) : - PerformUnitPartConversion(outInfo, targetInfo2, isInternal) - ); - if (tempInfo.Error.Type != ErrorTypes.None) - { - return tempInfo; - } - - outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - outInfo.Prefix = new Prefix(outInfo.Prefix.PrefixUsage); - outInfo.Value = tempInfo.Value; - outInfo.BaseTenExponent = tempInfo.BaseTenExponent; - - if (!isInternal) - { - //When the target unit has a prefix, the conversion is adapted to it (e.g., lb to kg is 0.453). - //Such an output isn't always desirable (kg isn't a valid unit, but g + kilo); that's why the output - //value has to be multiplied by the prefix when reaching this point (i.e., result delivered to the user). - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, targetInfo.Prefix.Factor, Operations.Multiplication - ); - } - } - - return outInfo; - } - - //Called before starting unit-part conversions. - static ErrorTypes GetUnitPartConversionError(UnitPart originalPart, UnitPart targetPart) - { - ErrorTypes outError = ErrorTypes.None; - - if (MethodsCommon.GetTypeFromUnitPart(originalPart) != MethodsCommon.GetTypeFromUnitPart(targetPart)) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (MethodsCommon.IsUnnamedUnit(originalPart.Unit) || MethodsCommon.IsUnnamedUnit(targetPart.Unit)) - { - //Finding an unnamed compound here would be certainly an error. - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo AdaptPartToConversion(UnitPart unitPart, int exponent) - { - UnitInfo outInfo = MethodsCommon.UnitPartToUnitInfo(unitPart); - if (outInfo.Unit == Units.Centimetre) - { - //To avoid inconsistencies with individual unit conversions. - outInfo.Unit = Units.Metre; - outInfo.BaseTenExponent -= 2; - } - - if (unitPart.Prefix.Factor != 1 && exponent != 1) - { - UnitInfo prefixInfo = Managed.RaiseToIntegerExponent - ( - unitPart.Prefix.Factor, exponent - ); - - outInfo.Prefix = new Prefix(); - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, prefixInfo, Operations.Multiplication - ); - } - - return outInfo; - } - - @SuppressWarnings("serial") - static ArrayList GetUnitPartsConversion(UnitPart part1, UnitPart part2) - { - ArrayList unitParts = new ArrayList() - {{ - //Exponent signs will be managed at a later stage. - add(new UnitPart(part1) {{ Exponent = Math.abs(part1.Exponent); }}); - add(new UnitPart(part2) {{ Exponent = Math.abs(part2.Exponent); }}); - }}; - - ArrayList tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) return tempParts; - - int count = 0; - while (count < 2) - { - count = count + 1; - int i = 0; - int i2 = 1; - if (count == 2) - { - i = 1; - i2 = 0; - } - - for (int i11 = unitParts.get(i).Exponent; i11 > 0; i11--) - { - unitParts.get(i).Exponent = i11; - for (int i22 = unitParts.get(i2).Exponent; i22 > 0; i22--) - { - unitParts.get(i2).Exponent = i22; - tempParts = GetUnitPartsConversionSameType(unitParts); - if (tempParts != null) - { - //Accounts for scenarios on the lines of m3/L2. - return tempParts; - } - } - } - } - - return null; - } - - static ArrayList GetUnitPartsConversionSameType(ArrayList unitParts) - { - if (MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(0).Unit, 1.0)) == MethodsCommon.GetTypeFromUnitInfo(ExceptionInstantiation.NewUnitInfo(unitParts.get(1).Unit, 1.0))) - { - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0)) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1))) - { - return unitParts; - } - else if (MethodsCommon.GetTypeFromUnitPart(unitParts.get(0), true) == MethodsCommon.GetTypeFromUnitPart(unitParts.get(1), true)) - { - //Cases like m2/ft3 recognised as length. Exponents are being managed later. - unitParts.get(0).Exponent = 1; - unitParts.get(1).Exponent = 1; - - return unitParts; - } - - return null; - } - - //Called before starting any unit conversion. - static ErrorTypes GetConversionError(UnitInfo originalInfo, UnitInfo targetInfo) - { - ErrorTypes outError = ErrorTypes.None; - - if (originalInfo.Unit == Units.None || targetInfo.Unit == Units.None) - { - outError = ErrorTypes.InvalidUnit; - } - else if (originalInfo.Unit == Units.Unitless || targetInfo.Unit == Units.Unitless) - { - outError = ErrorTypes.InvalidUnitConversion; - } - else if (originalInfo.Error.Type != ErrorTypes.None) - { - outError = originalInfo.Error.Type; - } - else if (targetInfo.Error.Type != ErrorTypes.None) - { - outError = targetInfo.Error.Type; - } - else if (originalInfo.Type == UnitTypes.None || originalInfo.Type != targetInfo.Type) - { - if (originalInfo.Parts.size() == targetInfo.Parts.size()) - { - int partMatchCount = (int)originalInfo.Parts.stream().filter - ( - x -> Linq.FirstOrDefault - ( - targetInfo.Parts, y -> y.Exponent.equals(x.Exponent) && y.Unit.equals(x.Unit), null - ) - != null - ) - .count(); - - if (partMatchCount == originalInfo.Parts.size()) - { - //In some cases, different types might be intrinsically identical (= same unit parts). - return outError; - } - } - outError = ErrorTypes.InvalidUnitConversion; - } - - return outError; - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target) - { - return PerformUnitPartConversion(convertInfo, target, true); - } - - static UnitInfo PerformUnitPartConversion(UnitInfo convertInfo, UnitInfo target, boolean isInternal) - { - ConversionItems conversionItems = GetAllUnitPartDict(convertInfo.Parts, target.Parts); - - if (conversionItems.ConvertInfo != null) - { - convertInfo = Managed.PerformManagedOperationUnits - ( - convertInfo, conversionItems.ConvertInfo, Operations.Multiplication - ); - } - - return - ( - conversionItems.OutDict.size() == 0 ? - ExceptionInstantiation.NewUnitInfo(convertInfo, ErrorTypes.InvalidUnitConversion) - : ConvertAllUnitParts - ( - convertInfo, conversionItems.OutDict, isInternal - ) - ); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts) - { - return ConvertAllUnitParts(convertInfo, allParts, true); - } - - static UnitInfo ConvertAllUnitParts(UnitInfo convertInfo, HashMap allParts, boolean isInternal) - { - for (Map.Entry item: allParts.entrySet()) - { - convertInfo = ConvertUnitPartToTarget - ( - convertInfo, item.getKey(), item.getValue(), isInternal - ); - - if (convertInfo.Error.Type != ErrorTypes.None) - { - return convertInfo; - } - } - - return convertInfo; - } - - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets) - { - return GetAllUnitPartDict(originals, targets, true); - } - - //Relates all the original/target unit parts between each other in order to facilitate the subsequent unit conversion. - static ConversionItems GetAllUnitPartDict(ArrayList originals, ArrayList targets, boolean findCommonPartMatches) - { - ConversionItems conversionItems = new ConversionItems(originals, targets); - - for (UnitPart original: originals) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(original); - - UnitPart target = Linq.FirstOrDefault - ( - targets, x -> MethodsCommon.GetTypeFromUnitPart(x).equals(type), null - ); - if (target == null || target.Unit == Units.None) continue; - - conversionItems.OutDict.put(original, target); - } - - if (conversionItems.OutDict.size() < Math.max(originals.size(), targets.size())) - { - if (findCommonPartMatches) - { - conversionItems = GetUnitPartDictInCommon - ( - new ConversionItems(originals, targets) - ); - } - else conversionItems.OutDict = new HashMap(); - } - - return conversionItems; - } - - //In some cases, the GetAllUnitPartDict approach doesn't work. For example: BTU/s and W. - //Note that ignoring the dividable/non-dividable differences right away (useful in other situations) isn't good here. - //The only solution is looking for common parts to both units (always the case, by bearing in mind that have the same type). - //In the aforementioned example of BTU/s to W, the two pairs BTU-J and s-s will be returned. - static ConversionItems GetUnitPartDictInCommon(ConversionItems conversionItems) - { - conversionItems = GetNonDividableUnitPartDictInCommon(conversionItems); - - if ((conversionItems.Originals.size() == conversionItems.Targets.size() && conversionItems.Originals.size() == 0)) - { - //No originals/targets left would mean that no further analysis is required. - //Not having found anything (conversionItems.OutDict empty) is OK on account of the fact that - //unmatched non-dividables might have been converted into a dividable version. - return conversionItems; - } - - //Trying to match the remaining parts (i.e., individual units not matching any non-dividable compound). - ConversionItems conversionItems2 = GetAllUnitPartDict - ( - conversionItems.Originals, conversionItems.Targets, false - ); - if (conversionItems2.OutDict.size() == 0) return conversionItems2; - - for (Map.Entry item2: conversionItems2.OutDict.entrySet()) - { - conversionItems.OutDict.put(item2.getKey(), item2.getValue()); - } - - return conversionItems; - } - - //Method looking for proper matches for each non-dividable compound. For example, BTU might be - //matched with kg*m/s2 (= N). - static ConversionItems GetNonDividableUnitPartDictInCommon(ConversionItems conversionItems) - { - int count = 0; - while (count < 2 && (conversionItems.Originals.size() > 0 && conversionItems.Targets.size() > 0)) - { - count = count + 1; - if (count == 1) - { - conversionItems.Others = conversionItems.Targets; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Originals); - } - else - { - conversionItems.Others = conversionItems.Originals; - conversionItems.NonDividables = GetNonDividableParts(conversionItems.Targets); - } - - for (int i = conversionItems.NonDividables.size() - 1; i >= 0; i--) - { - if (conversionItems.Others.size() == 0) return new ConversionItems(); - - conversionItems = MatchNonDividableParts(conversionItems, i); - if (conversionItems.TempPair.getKey() == null || conversionItems.TempPair.getKey().Unit == Units.None) - { - //After not having found a direct match for the given non-dividable, an indirect - //approach (via its type) will be tried. - conversionItems = ReplaceUnmatchedNonDividable - ( - conversionItems, count, i - ); - - if (conversionItems.Originals.size() == 0) return conversionItems; - - continue; - } - - //A proper match for the non-divididable part was found. - //That is, a set of common parts in others which also form a valid compound. - conversionItems = UpdateConversionItems(conversionItems, count, i); - } - } - - return conversionItems; - } - - static ConversionItems UpdateConversionItems(ConversionItems conversionItems, int count, int i) - { - return UpdateOutDict - ( - RemoveNonDividable(conversionItems, count, i), count - ); - } - - static ConversionItems UpdateOutDict(ConversionItems conversionItems, int count) - { - Map.Entry tempPair = - ( - count == 1 ? - new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getKey(), conversionItems.TempPair.getValue() - ) - : new AbstractMap.SimpleEntry - ( - conversionItems.TempPair.getValue(), conversionItems.TempPair.getKey() - ) - ); - - conversionItems.OutDict.put(tempPair.getKey(), tempPair.getValue()); - - return conversionItems; - } - - static ConversionItems RemoveNonDividable(ConversionItems conversionItems, int count, int i) - { - if (conversionItems.NonDividables.size() - 1 < i) return conversionItems; - - conversionItems.NonDividables.remove(i); - - //Originals & Targets are automatically updated with any modification in Others. - //Not the case with NonDividables, that's why having to call this method. - return RemoveNonDividableOriginals(conversionItems, count); - } - - static ConversionItems RemoveNonDividableOriginals(ConversionItems conversionItems, int count) - { - ArrayList nonOriginals = - ( - count == 1 ? conversionItems.Originals : conversionItems.Targets - ); - - for (int i = nonOriginals.size() - 1; i >= 0; i--) - { - if (!HCUnits.AllNonDividableUnits.contains(nonOriginals.get(i).Unit)) continue; - - if (!conversionItems.NonDividables.contains(nonOriginals.get(i))) - { - nonOriginals.remove(i); - } - } - - return conversionItems; - } - - //Method trying to match each item of conversionItems.NonDividables with parts of conversionItems.Others. - //Bear in mind that the goal isn't just looking for sets of unit parts defining the given type; they have - //also to be associated with a valid compound unit. For example: when trying to match the force unit lbf, - //lb*ft/s2 wouldn't be a good match; these parts do define a force, but not a supported unit. A good match - //would be kg*m/s2, which also defines the supported unit newton. - //It is necessary to find a supported unit because this is the way to get a conversion factor; just converting - //the parts would output a wrong result. In the aforementioned example, lb*ft/s2 doesn't equal lbf (otherwise, - //lbf would be defined as a compound precisely formed by these parts). - static ConversionItems MatchNonDividableParts(ConversionItems conversionItems, int i) - { - conversionItems.TempPair = new AbstractMap.SimpleEntry(null, null); - - UnitPart matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> x.Unit.equals(conversionItems.NonDividables.get(i).Unit), null - ); - - if (matchedPart != null) - { - conversionItems.Others.remove(matchedPart); - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), matchedPart - ); - - return conversionItems; - } - - ConversionItems origConversionItems = new ConversionItems(conversionItems); - - ArrayList parts2 = new ArrayList(); - for (CompoundPart nonPart: HCCompounds.AllCompounds.get(MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i))).get(0).Parts) - { - matchedPart = Linq.FirstOrDefault - ( - conversionItems.Others, x -> nonPart.Type.equals(MethodsCommon.GetTypeFromUnit(x.Unit)), null - ); - - if (matchedPart == null) - { - return origConversionItems; - } - - //Exponent of the corresponding conversionItems.Others part after having - //removed the current nonPart. This exponent doesn't have to match the one - //of the associated type (i.e., the one being stored in parts2). - int exponent = matchedPart.Exponent - - ( - (int)Math.signum(conversionItems.NonDividables.get(i).Exponent) * nonPart.Exponent - ); - - parts2.add - ( - new UnitPart(matchedPart.Unit, nonPart.Exponent) - ); - conversionItems.Others.remove(matchedPart); - - if (exponent != 0) - { - conversionItems.Others.add - ( - UnitPartInternal.NewUnitPart - ( - matchedPart.Unit, - matchedPart.Prefix.Factor, - exponent - ) - ); - } - } - - UnitInfo tempInfo = MethodsCommon.GetCompoundUnitFromParts - ( - MethodsCommon.GetPartsFromUnit - ( - ExceptionInstantiation.NewUnitInfo(parts2) - ) - ); - - if (tempInfo.Unit == Units.None) - { - //Condition avoiding situations like assuming that lb*ft/s2 & lbf are identical. - return origConversionItems; - } - - conversionItems.TempPair = new AbstractMap.SimpleEntry - ( - conversionItems.NonDividables.get(i), UnitPartInternal.NewUnitPart - ( - tempInfo.Unit, tempInfo.Prefix.Factor, - conversionItems.NonDividables.get(i).Exponent - ) - ); - - return conversionItems; - } - - static ArrayList GetNonDividableParts(ArrayList iniList) - { - ArrayList outList = Linq.Where - ( - iniList, x -> HCUnits.AllNonDividableUnits.contains(x.Unit) - ); - - HashMap types = new HashMap(); - for (int i = outList.size() - 1; i >= 0; i--) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(outList.get(i)); - if (!HCCompounds.AllCompounds.containsKey(type)) - { - //Theoretically, this shouldn't ever happen because AllNonDividableUnits - //is expected to only contain compounds. On the other hand, an error here - //wouldn't be that weird and, in any case, not too influential. That's why - //this in-the-safest-scenario check is acceptable. - outList.remove(i); - } - else types.put(outList.get(i), type); - } - - return Linq.OrderByDescending - ( - outList, new Comparator() - { - //Original C# code: x -> HCCompounds.AllCompounds.get(types[x]).get(0).Parts.Count - public int compare(UnitPart first, UnitPart second) - { - return new Integer(HCCompounds.AllCompounds.get(types.get(first)).get(0).Parts.size()).compareTo - ( - HCCompounds.AllCompounds.get(types.get(second)).get(0).Parts.size() - ); - } - } - ); - } - - static ConversionItems ReplaceUnmatchedNonDividable(ConversionItems conversionItems, int count, int i) - { - UnitTypes type = MethodsCommon.GetTypeFromUnitPart(conversionItems.NonDividables.get(i), false, true); - - if - ( - !HCCompounds.AllBasicCompounds.containsKey(type) || - !(HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) || - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.CGS)) - ) - { - //A hardcoding mistake is the most likely reason for having reached this point. - //Firstly, all the non-dividable units are supposed to be compounds. On the other hand, all the compounds - //are expected to be represented by, at least, one unit (included in AllBasicCompounds). Although it is - //possible to have a type with no SI units, such a case shouldn't get here. Note that non-dividable are - //expected to be defined as opposed to an existing dividable alternative (e.g., SI compound in that type). - return new ConversionItems(); - } - - Units targetUnit = - ( - HCCompounds.AllBasicCompounds.get(type).containsKey(UnitSystems.SI) ? - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.SI) : - HCCompounds.AllBasicCompounds.get(type).get(UnitSystems.CGS) - ); - - return RemoveNonDividable - ( - PerformNonDividableReplacement - ( - conversionItems, count, i, targetUnit - ), - count, i - ); - } - - static ConversionItems PerformNonDividableReplacement(ConversionItems conversionItems, int count, int i, Units targetUnit) - { - conversionItems.ConvertInfo = ConvertUnit - ( - MethodsCommon.UnitPartToUnitInfo(conversionItems.NonDividables.get(i)), - MethodsCommon.UpdateMainUnitVariables(ExceptionInstantiation.NewUnitInfo(targetUnit)), false - ); - - if (conversionItems.ConvertInfo.Error.Type != ErrorTypes.None) - { - return new ConversionItems(); - } - - ArrayList list = - ( - count == 1 ? - conversionItems.Originals : - conversionItems.Targets - ); - - list.remove(conversionItems.NonDividables.get(i)); - list.addAll(MethodsCommon.GetBasicCompoundUnitParts(targetUnit)); - - UnitInfo tempInfo = MethodsCommon.SimplifyCompoundComparisonUnitParts(list, true); - list = new ArrayList(tempInfo.Parts); - //The simplification actions might have increased the output value via prefix compensation. - conversionItems.ConvertInfo = Managed.PerformManagedOperationUnits - ( - conversionItems.ConvertInfo, tempInfo, Operations.Multiplication - ); - - if (count == 1) - { - conversionItems.Originals = new ArrayList(list); - } - else - { - conversionItems.Targets = new ArrayList(list); - } - - return conversionItems; - } - - static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo) - { - return ConvertUnit(originalInfo, targetInfo, true); - } - - public static UnitInfo ConvertUnit(UnitInfo originalInfo, UnitInfo targetInfo, boolean isInternal) - { - return PerformConversion - ( - originalInfo, targetInfo, isInternal - ); - } - - //This function expects targetInfo2 to be normalised. - static UnitInfo AccountForTargetUnitPrefixes(UnitInfo originalInfo, UnitInfo targetInfo2) - { - int newExponent = GetBaseTenExponentIncreasePrefixes - ( - originalInfo, targetInfo2.BaseTenExponent - ); - - return Managed.NormaliseUnitInfo - ( - //Prefix.Factor is already included in newExponent. - ExceptionInstantiation.NewUnitInfo - ( - originalInfo, newExponent, new Prefix(originalInfo.Prefix.PrefixUsage) - ) - ); - } - - static int GetBaseTenExponentIncreasePrefixes(UnitInfo originalInfo, int targetInfo2Exp) - { - //targetInfo2 is being normalised by only accounting for the value information which is - //relevant to the conversion (i.e., the prefix). - UnitInfo originalTemp = ExceptionInstantiation.NewUnitInfo(originalInfo, 1.0, 0); - originalTemp = Managed.NormaliseUnitInfo(originalTemp); - - return originalTemp.BaseTenExponent - targetInfo2Exp; - } - - static UnitInfo NormaliseTargetUnit(UnitInfo targetInfo, boolean isInternal) - { - UnitInfo outInfo = ExceptionInstantiation.NewUnitInfo(targetInfo); - - if (isInternal) - { - //The only relevant part of the target unit value should ideally be the prefix. - //Such an assumption isn't always compatible with external conversions; in these cases, - //the target unit might have been parsed (+ auto-converted) and, consequently, other - //values might have to be also considered. - outInfo.Value = 1.0; - outInfo.BaseTenExponent = 0; - } - - return Managed.NormaliseUnitInfo(outInfo); - } - - //Determines whether the conversion might be performed directly. That is: by only considering the - //main unit information (i.e., Units enum member), rather than its constituent parts. - static boolean UnitsCanBeConvertedDirectly(UnitInfo original, UnitInfo target) - { - if (original.Unit != Units.None && original.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(original.Unit)) - { - if (target.Unit != Units.None && target.Unit != Units.Unitless && !MethodsCommon.IsUnnamedUnit(target.Unit)) - { - return true; - } - } - - return false; - } - - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target) - { - return ConvertUnitValue(original, target, false); - } - - //The prefixes of both units are being managed before reaching this point. - static UnitInfo ConvertUnitValue(UnitInfo original, UnitInfo target, boolean inverseOutputs) - { - if - ( - original.Unit == Units.None || original.Unit == Units.Unitless || - target.Unit == Units.Unitless || target.Unit == Units.Unitless - ) - { - original.Error = ExceptionInstantiation.NewErrorInfo(ErrorTypes.InvalidUnit); - return original; - } - - //Both units have the same type. - if (original.Type != UnitTypes.None && SpecialConversionTypes.contains(original.Type)) - { - UnitInfo tempInfo = ConvertUnitValueSpecial(original, target); - return - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(1.0, tempInfo, Operations.Division) : - tempInfo - ); - } - else - { - UnitInfo original2 = GetUnitConversionFactor(original.Unit); - UnitInfo target2 = GetUnitConversionFactor(target.Unit); - UnitInfo convFactor = - ( - inverseOutputs ? - Managed.PerformManagedOperationUnits(target2, original2, Operations.Division) : - Managed.PerformManagedOperationUnits(original2, target2, Operations.Division) - ); - - return Managed.PerformManagedOperationUnits - ( - original, convFactor, Operations.Multiplication - ); - } - } - - static UnitInfo GetUnitConversionFactor(Units unit) - { - return - ( - HCMain.AllUnitConversionFactors.get(unit) < 0 ? - HCMain.AllBeyondDecimalConversionFactors.get(HCMain.AllUnitConversionFactors.get(unit)) : - ExceptionInstantiation.NewUnitInfo(HCMain.AllUnitConversionFactors.get(unit)) - ); - } - - //Takes care of conversions which do not rely on conversion factors. - static UnitInfo ConvertUnitValueSpecial(UnitInfo original, UnitInfo target) - { - UnitInfo convertInfo = ExceptionInstantiation.NewUnitInfo(original); - - if (original.Type == UnitTypes.Temperature) - { - convertInfo = ConvertTemperature(convertInfo, target.Unit); - } - - return convertInfo; - } - - static UnitInfo ConvertTemperature(UnitInfo outInfo, Units targetUnit) - { - if (targetUnit == Units.Kelvin) - { - outInfo = ConvertTemperatureToKelvin(outInfo); - } - else if (outInfo.Unit == Units.Kelvin) - { - outInfo = ConvertTemperatureFromKelvin - ( - ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit) - ); - } - else - { - outInfo = ConvertTemperatureToKelvin(ExceptionInstantiation.NewUnitInfo(outInfo)); - outInfo = ConvertTemperatureFromKelvin(ExceptionInstantiation.NewUnitInfo(outInfo, targetUnit)); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureToKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits(outInfo, 273.15, Operations.Addition); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - outInfo, 459.67, Operations.Addition - ), - 1.8, Operations.Division - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 1.8, Operations.Division - ); - } - - return outInfo; - } - - static UnitInfo ConvertTemperatureFromKelvin(UnitInfo outInfo) - { - if (outInfo.Unit == Units.DegreeCelsius) - { - outInfo = Managed.PerformManagedOperationUnits - ( - outInfo, 273.15, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeFahrenheit) - { - outInfo = Managed.PerformManagedOperationUnits - ( - Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ), - 459.67, Operations.Subtraction - ); - } - else if (outInfo.Unit == Units.DegreeRankine) - { - outInfo = Managed.PerformManagedOperationUnits - ( - 1.8, outInfo, Operations.Multiplication - ); - } - - return outInfo; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fe/f0a1810ef34c00171048b3f61ecb42d3 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fe/f0a1810ef34c00171048b3f61ecb42d3 deleted file mode 100644 index 317add6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/fe/f0a1810ef34c00171048b3f61ecb42d3 +++ /dev/null @@ -1,1222 +0,0 @@ -package UnitParser; - -import InternalUnitParser.CSharpAdaptation.*; -import InternalUnitParser.Classes.*; -import InternalUnitParser.Methods.*; -import InternalUnitParser.Operations.*; -import InternalUnitParser.Parse.*; - -import java.util.ArrayList; - -/**Basic UnitParser class containing all the information about units and values.**/ -public class UnitP implements Comparable -{ - /**Member of the Units enum which best suits the current conditions.**/ - public final Units Unit; - /**Member of the UnitTypes enum which best suits the current conditions.**/ - public final UnitTypes UnitType; - /**Member of the UnitSystems enum which best suits the current conditions.**/ - public final UnitSystems UnitSystem; - /**Prefix information affecting all the unit parts.**/ - public final Prefix UnitPrefix; - /**List containing the basic unit parts which define the current unit.**/ - public final ArrayList UnitParts; - /**String variable including the unit information which was input at variable instantiation.**/ - public final String OriginalUnitString; - /**String variable containing the symbol(s) best describing the current unit.**/ - public final String UnitString; - /**String variable including both numeric and unit information associated with the current conditions.**/ - public final String ValueAndUnitString; - /**Base-ten exponent used when dealing with too small/big numeric values.**/ - public final Integer BaseTenExponent; - /**ErrorInfo variable containing all the error- and exception-related information.**/ - public final ErrorInfo Error; - /**double variable storing the primary numeric information under the current conditions.**/ - public Double Value; - - static String StartHardcoding = CSharpOther.StartHarcoding(); - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unitString Unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(value, unitString, exceptionHandling, prefixUsage); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo(unitP2.ErrorType, unitP2.ExceptionHandling); - } - - /** - Initialises a new UnitP instance. - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage) - { - ErrorTypes parsingError = - ( - valueAndUnit == null ? ErrorTypes.NumericParsingError : ErrorTypes.None - ); - - UnitInfo unitInfo = ExceptionInstantiation.NewUnitInfo(0.0, exceptionHandling, prefixUsage); - - String unitString = ""; - - if (parsingError == ErrorTypes.None) - { - UnitInfo tempInfo = MethodsUnitP.ParseValueAndUnit(valueAndUnit); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - unitString = tempInfo.TempString; - unitInfo.Value = tempInfo.Value; - unitInfo.BaseTenExponent = tempInfo.BaseTenExponent; - } - else parsingError = tempInfo.Error.Type; - } - - if (parsingError != ErrorTypes.None && !valueAndUnit.contains(" ")) - { - //valueAndUnit is assumed to only contain unit information. - parsingError = ErrorTypes.None; - unitInfo.Value = 1.0; - unitString = valueAndUnit; - } - - UnitPConstructor unitP2 = MethodsUnitP.GetUnitP2(unitInfo, unitString); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.Factor, prefixUsage); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - (parsingError != ErrorTypes.None ? parsingError : unitP2.ErrorType), - unitP2.ExceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1.0 - Unit = Units.Unitless - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - **/ - public UnitP() - { - this(1.0); - } - - public UnitP(Double value) - { - this(value, Units.Unitless); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Value = 1m - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param unit Member of the Units enum to be used. - **/ - public UnitP(Units unit) - { - this(1.0, unit); - } - - /** - Initialises a new UnitP instance. - @param unitP variable whose information will be used. - **/ - public UnitP(UnitP unitP) - { - Value = unitP.Value; - BaseTenExponent = unitP.BaseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.OriginalUnitString; - ValueAndUnitString = unitP.ValueAndUnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** - Initialises a new UnitP instance. - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix, ExceptionHandlingTypes exceptionHandling) - { - ErrorTypes errorType = - ( - unit == Units.None || MethodsCommon.IsUnnamedUnit(unit) ? - ErrorTypes.InvalidUnit : ErrorTypes.None - ); - - UnitInfo tempInfo = null; - if (errorType == ErrorTypes.None) - { - //Getting the unit parts associated with the given unit. - tempInfo = ExceptionInstantiation.NewUnitInfo(value, unit, prefix); - - if (tempInfo.Error.Type == ErrorTypes.None) - { - tempInfo = MethodsUnitP.ImproveUnitInfo(tempInfo, false); - } - else errorType = tempInfo.Error.Type; - } - - if (errorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(prefix.PrefixUsage); - UnitParts = new ArrayList(); - UnitString = null; - OriginalUnitString = null; - Unit = Units.None; - UnitSystem = UnitSystems.None; - UnitType = UnitTypes.None; - ValueAndUnitString = ""; - } - else - { - Value = tempInfo.Value; - BaseTenExponent = tempInfo.BaseTenExponent; - Unit = unit; - UnitType = MethodsCommon.GetTypeFromUnit(Unit); - UnitSystem = MethodsCommon.GetSystemFromUnit(Unit); - UnitPrefix = new Prefix(prefix); - UnitParts = tempInfo.Parts; - UnitString = MethodsCommon.GetUnitString(tempInfo); - OriginalUnitString = UnitString; - ValueAndUnitString = Value.toString() + " " + UnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - errorType, exceptionHandling - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - **/ - public UnitP(Double value, String unitString) - { - this - ( - value, unitString, ExceptionHandlingTypes.NeverTriggerException, - PrefixUsageTypes.DefaultUsage - ); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP - ( - Double value, String unitString, ExceptionHandlingTypes exceptionHandling - ) - { - this (value, unitString, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unitString String containing the unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, String unitString, PrefixUsageTypes prefixUsage) - { - this(value, unitString, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - **/ - public UnitP(String valueAndUnit) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param valueAndUnit String containing the value and unit information to be parsed. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(String valueAndUnit, ExceptionHandlingTypes exceptionHandling) - { - this(valueAndUnit, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param valueAndUnit String containing the value and unit information to be parsed. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(String valueAndUnit, PrefixUsageTypes prefixUsage) - { - this(valueAndUnit, ExceptionHandlingTypes.NeverTriggerException, prefixUsage); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefix Prefix variable whose information will be used. - **/ - public UnitP(Double value, Units unit, Prefix prefix) - { - this(value, unit, prefix, ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - **/ - public UnitP(Double value, Units unit) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - PrefixUsage = PrefixUsageTypes.DefaultUsage - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param exceptionHandling Member of the ExceptionHandlingTypes enum to be used. - **/ - public UnitP(Double value, Units unit, ExceptionHandlingTypes exceptionHandling) - { - this(value, unit, new Prefix(), exceptionHandling); - } - - /** - Initialises a new UnitP instance. - Automatically assigned values: - Error.ExceptionHandling = ExceptionHandlingTypes.NeverTriggerException - @param value Numeric value to be used. - @param unit Member of the Units enum to be used. - @param prefixUsage Member of the PrefixUsageTypes enum to be used. - **/ - public UnitP(Double value, Units unit, PrefixUsageTypes prefixUsage) - { - this(value, unit, new Prefix(), ExceptionHandlingTypes.NeverTriggerException); - } - - - //---------------------------- Private UnitP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, Double value, int baseTenExponent) - { - Value = value; - BaseTenExponent = baseTenExponent; - Unit = unitP.Unit; - UnitType = unitP.UnitType; - UnitSystem = unitP.UnitSystem; - UnitPrefix = new Prefix(unitP.UnitPrefix); - UnitParts = new ArrayList(unitP.UnitParts); - UnitString = unitP.UnitString; - OriginalUnitString = unitP.Value.toString() + - ( - unitP.BaseTenExponent != 0 ? - "*10^" + unitP.BaseTenExponent.toString() : "" - ); - ValueAndUnitString = Value.toString() + - ( - BaseTenExponent != 0 ? - "*10^" + BaseTenExponent.toString() : "" - ) + " " + UnitString; - Error = new ErrorInfo(unitP.Error); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo) - { - this(parseInfo, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(ParseInfo parseInfo, String originalUnitString) - { - this(parseInfo, originalUnitString, UnitSystems.None); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system - ) - { - this(parseInfo, originalUnitString, system, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, ExceptionHandlingTypes exceptionHandling - ) - { - this(parseInfo, originalUnitString, system, exceptionHandling, PrefixUsageTypes.DefaultUsage); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, prefixUsage, false - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement - ) - { - this - ( - parseInfo, originalUnitString, system, exceptionHandling, - prefixUsage, noPrefixImprovement, true - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - ParseInfo parseInfo, String originalUnitString, UnitSystems system, - ExceptionHandlingTypes exceptionHandling, PrefixUsageTypes prefixUsage, - boolean noPrefixImprovement, boolean improveFinalValue - ) - { - UnitPConstructor unitP2 = new UnitPConstructor - ( - originalUnitString, parseInfo.UnitInfo, parseInfo.UnitInfo.Type, parseInfo.UnitInfo.System, - ErrorTypes.None, exceptionHandling, noPrefixImprovement, improveFinalValue - ); - - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = - ( - system != UnitSystems.None ? - system : unitP2.UnitSystem - ); - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitP unitP, ErrorTypes errorType) - { - this(unitP, errorType, ExceptionHandlingTypes.NeverTriggerException); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitP unitP, ErrorTypes errorType, ExceptionHandlingTypes exceptionHandling - ) - { - if (unitP == null) unitP = new UnitP(); - - UnitPConstructor unitP2 = new UnitPConstructor - ( - unitP.OriginalUnitString, ExceptionInstantiation.NewUnitInfo(unitP), - UnitTypes.None, UnitSystems.None, errorType, - ( - exceptionHandling != ExceptionHandlingTypes.NeverTriggerException ? - exceptionHandling : unitP.Error.ExceptionHandling - ) - ); - - if (unitP2.ErrorType != ErrorTypes.None) - { - Value = 0.0; - BaseTenExponent = 0; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix.PrefixUsage); - UnitParts = new ArrayList(); - Unit = Units.None; - UnitType = UnitTypes.None; - UnitSystem = UnitSystems.None; - OriginalUnitString = ""; - ValueAndUnitString = ""; - UnitString = ""; - } - else - { - OriginalUnitString = unitP2.OriginalUnitString; - Value = unitP2.Value; - BaseTenExponent = unitP2.UnitInfo.BaseTenExponent; - Unit = unitP2.UnitInfo.Unit; - UnitType = unitP2.UnitType; - UnitSystem = unitP2.UnitSystem; - UnitPrefix = new Prefix(unitP2.UnitInfo.Prefix); - UnitParts = unitP2.UnitInfo.Parts; - UnitString = unitP2.UnitString; - ValueAndUnitString = unitP2.ValueAndUnitString; - } - - //If applicable, this instantiation would trigger an exception right away. - Error = ExceptionInstantiation.NewErrorInfo - ( - unitP2.ErrorType, unitP2.ExceptionHandling - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, boolean noPrefixImprovement) - { - this - ( - new ParseInfo(unitInfo), unitP.OriginalUnitString, unitP.UnitSystem, - unitP.Error.ExceptionHandling, unitP.UnitPrefix.PrefixUsage, noPrefixImprovement - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP) - { - this(unitInfo, unitP, ""); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP(UnitInfo unitInfo, UnitP unitP, String originalUnitString) - { - this(unitInfo, unitP, originalUnitString, true); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public UnitP - ( - UnitInfo unitInfo, UnitP unitP, String originalUnitString, boolean improveFinalValue - ) - { - this - ( - new ParseInfo(unitInfo), originalUnitString, UnitSystems.None, - unitP.Error.ExceptionHandling, unitInfo.Prefix.PrefixUsage, - false, improveFinalValue - ); - } - - - //---------------------------- Public static methods. - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit) - { - return ConvertTo(unitP, targetUnit, null); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnit and targetPrefix. - **/ - public static UnitP ConvertTo(UnitP unitP, Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnit, targetPrefix); - } - - /** - Converts the input unit into the target one. Different unit types will trigger an error. - @param unitP variable whose unit will be converted. - @param targetUnitString String representation of the conversion target unit. - @return UnitP variable containing the information resulting from converting unitP to targetUnitString. - **/ - public static UnitP ConvertTo(UnitP unitP, String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(unitP, targetUnitString); - } - - /** - Returns the String representations associated with the input unit. - otherStringsToo = false - @param unit Unit whose String representations will be returned. - @return ArrayList variable including all the primary string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit) - { - return GetStringsForUnit(unit, false); - } - - /** - Returns the String representations associated with the input unit. - @param unit Unit whose String representations will be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with unit. - **/ - public static final ArrayList GetStringsForUnit(Units unit, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(unit, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @return ArrayList variable including all the primary string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, false); - } - - /** - Returns the String representations associated with the input unit type. - @param unitType Type of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with all the units related to unitType. - **/ - public static final ArrayList GetStringsForType(UnitTypes unitType, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(unitType, otherStringsToo); - } - - /** - Returns the String representations associated with the input unit type and system. - otherStringsToo = false - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @return ArrayList variable including all the primary string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, false); - } - - /** - Returns the String representations associated with the input unit type and system. - @param unitType Type of the unit String representations to be returned. - @param unitSystem System of the unit String representations to be returned. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - @return ArrayList variable including all the (primary or primary and secondary) string representations associated with all the units related to unitType and unitSystem. - **/ - public static final ArrayList GetStringsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem, boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon(unitType, unitSystem, otherStringsToo); - } - - /** - Returns the members of the Units enum which are associated with the input unit type. - @param unitType Type of the units to be returned. - @return ArrayList variable including all the units associated with unitType. - **/ - public static final ArrayList GetUnitsForType(UnitTypes unitType) - { - return MethodsUnitP.GetUnitsTypeCommon(unitType); - } - - /** - Returns the members of the Units enum which are associated with the input unit type and system. - @param unitType Type of the units to be returned. - @param unitSystem System of the units to be returned. - @return ArrayList variable including all the units associated with unitType and unitSystem. - **/ - public static final ArrayList GetUnitsForTypeAndSystem(UnitTypes unitType, UnitSystems unitSystem) - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(unitType, unitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the input unit. - @param unit Unit whose type will be returned. - @return UnitTypes variable associated with unit. - **/ - public static UnitTypes GetUnitType(Units unit) - { - return MethodsCommon.GetTypeFromUnit(unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the input unit. - @param unit Unit whose system will be returned. - @return UnitSystems variable associated with unit. - **/ - public static UnitSystems GetUnitSystem(Units unit) - { - return MethodsCommon.GetSystemFromUnit(unit, false, true); - } - - /** - Removes the global prefix of the input UnitP variable. - @param unitP variable whose prefix will be removed. - **/ - public static UnitP RemoveGlobalPrefix(UnitP unitP) - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ), - unitP, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - @param unitP variable whose base-ten exponent will be removed. - **/ - public static UnitP RemoveBaseTen(UnitP unitP) - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(unitP) - ); - - return new UnitP(unitP, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public non-static methods. - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - targetPrefix = null - @param targetUnit Conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, null); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnit Conversion target unit. - @param targetPrefix Prefix of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(Units targetUnit, Prefix targetPrefix) - { - return MethodsUnitP.ConvertToCommon(this, targetUnit, targetPrefix); - } - - /** - Converts the current unit into the target one. Different unit types will trigger an error. - @param targetUnitString String representation of the conversion target unit. - **/ - public UnitP ConvertCurrentUnitTo(String targetUnitString) - { - return MethodsUnitP.ConvertToCommon(this, targetUnitString); - } - - /** - Returns the String representations associated with the current unit. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentUnit() - { - return GetStringsForCurrentUnit(false); - } - - /** - Returns the String representations associated with the current unit. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentUnit(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsUnitCommon(Unit, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentType() - { - return GetStringsForCurrentType(false); - } - - /** - Returns the String representations associated with the current unit type. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentType(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeCommon(UnitType, otherStringsToo); - } - - /** - Returns the String representations associated with the current unit type and system. - otherStringsToo = false - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem() - { - return GetStringsForCurrentTypeAndSystem(false); - } - - /** - Returns the String representations associated with the current unit type and system. - @param otherStringsToo When true, all the supported String representations (case doesn't matter) other than symbols (case matters) are also included. - **/ - public final ArrayList GetStringsForCurrentTypeAndSystem(boolean otherStringsToo) - { - return MethodsUnitP.GetStringsTypeAndSystemCommon - ( - UnitType, UnitSystem, otherStringsToo - ); - } - - /** - Returns the members of the Units enum which are associated with the current unit type. - **/ - public final ArrayList GetUnitsForCurrentType() - { - return MethodsUnitP.GetUnitsTypeCommon(UnitType); - } - - /** - Returns the members of the Units enum which are associated with the current unit type and system. - **/ - public final ArrayList GetUnitsForCurrentTypeAndSystem() - { - return MethodsUnitP.GetUnitsTypeAndSystemCommon(UnitType, UnitSystem); - } - - /** - Returns the member of the UnitTypes enum which is associated with the current unit. - **/ - public UnitTypes GetCurrentUnitType() - { - return MethodsCommon.GetTypeFromUnit(Unit); - } - - /** - Returns the member of the UnitSystems enum which is associated with the current unit. - **/ - public UnitSystems GetCurrentUnitSystem() - { - return MethodsCommon.GetSystemFromUnit(Unit, false, true); - } - - /** - Removes the global prefix of the current UnitP variable. - **/ - public UnitP RemoveCurrentGlobalPrefix() - { - return new UnitP - ( - Managed.NormaliseUnitInfo - ( - ExceptionInstantiation.NewUnitInfo(this) - ), - this, true - ); - } - - /** - Transfers all the base-ten exponent information to the Value field (if possible). - **/ - public UnitP RemoveCurrentBaseTen() - { - UnitInfo tempInfo = Managed.ConvertBaseTenToValue - ( - ExceptionInstantiation.NewUnitInfo(this) - ); - - return new UnitP(this, tempInfo.Value, tempInfo.BaseTenExponent); - } - - - //---------------------------- Public error-related classes. - - public static class ErrorInfo - { - /**Error type.**/ - public final UnitP.ErrorTypes Type; - /**Exception handling type.**/ - public final UnitP.ExceptionHandlingTypes ExceptionHandling; - /**Error message.**/ - public final String Message; - - /**Initialises a new ErrorInfo instance.**/ - public ErrorInfo() - { - Type = UnitP.ErrorTypes.None; - ExceptionHandling = UnitP.ExceptionHandlingTypes.AlwaysTriggerException; - Message = ""; - } - - /** - Initialises a new ErrorInfo instance. - @param errorInfo ErrorInfo variable whose information will be used. - **/ - public ErrorInfo(ErrorInfo errorInfo) - { - if (errorInfo == null) errorInfo = new ErrorInfo(); - - Type = errorInfo.Type; - ExceptionHandling = errorInfo.ExceptionHandling; - Message = errorInfo.Message; - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type) throws Exception - { - this(type, UnitP.ExceptionHandlingTypes.NeverTriggerException); - } - - /**Initialises a new ErrorInfo instance. - @param type Member of the UnitP.ErrorTypes enum to be used. - @param exceptionHandling Member of the UnitP.ExceptionHandlingTypes enum to be used. - **/ - public ErrorInfo(UnitP.ErrorTypes type, UnitP.ExceptionHandlingTypes exceptionHandling) throws Exception - { - Type = type; - ExceptionHandling = exceptionHandling; - Message = GetMessage(type); - - if (type != UnitP.ErrorTypes.None && ExceptionHandling == UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - { - throw new Exception(Message); - } - } - - private String GetMessage(UnitP.ErrorTypes type) - { - String outString = ""; - - if (type == UnitP.ErrorTypes.InvalidOperation) - { - outString = "Invalid Operation. Some operands are incompatible among them or refer to invalid units."; - } - else if (type == UnitP.ErrorTypes.InvalidUnit) - { - outString = "Invalid Input. The input string doesn't match any supported unit."; - } - else if (type == UnitP.ErrorTypes.NumericError) - { - outString = "Numeric Error. An invalid mathematical operation has been performed."; - } - else if (type == UnitP.ErrorTypes.NumericParsingError) - { - outString = "Numeric Parsing Error. The input doesn't match the expected number + space + unit format."; - } - else if (type == UnitP.ErrorTypes.InvalidUnitConversion) - { - outString = "Invalid Unit Conversion. The unit conversion cannot be performed with these inputs."; - } - - return outString; - } - - @Override - /** - Determines whether the current ErrorInfo instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ErrorInfo)obj); - } - - boolean Equals(ErrorInfo other) - { - return - ( - other == null ? false : - Equals.ErrorsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ErrorInfo instance.**/ - public int hashCode() { return 0; } - } - - /**Contains all the supported error types.**/ - public enum ErrorTypes - { - /**No error.**/ - None, - - /** - Associated with invalid operations between UnitP variables not provoked by numeric errors. - Examples: addition of UnitP variables with different types; multiplication of UnitP variables outputting an unsupported unit. - **/ - InvalidOperation, - /** - Associated with faulty instantiations of UnitP variables. - Examples: relying on an unsupported input string; including prefixes not supported in that specific context. - **/ - InvalidUnit, - /** - Associated with invalid operations provoked by numeric overflow or arithmetic errors. - Examples: multiplication of too big values; division by zero. - **/ - NumericError, - /** - Associated with errors triggered when parsing numeric inputs. - Example: new UnitP("no-number unit") rather than new UnitP("number unit"). - **/ - NumericParsingError, - /** - Associated with invalid or unsupported conversions. - Example: UnitP("1 m/s").ConvertCurrentUnitTo("m/s2"). - **/ - InvalidUnitConversion, - } - - /**Determines whether errors trigger an exception or not.**/ - public enum ExceptionHandlingTypes - { - /**Errors never trigger an exception. Equivalent to standard .NET TryParse methods.**/ - NeverTriggerException, - /**Error always trigger an exception. Equivalent to standard .NET Parse methods.**/ - AlwaysTriggerException - } - - - //---------------------------- Public arithmetic operations emulating operator overloads in the original C# code. - - /** - Adds two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Augend. In case of incompatibilities, its configuration would prevail. - @param second Addend. - **/ - public static UnitP Addition(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Addition, - OperationsOther.GetOperationString(first, second, Operations.Addition) - ); - } - - /** - Subtracts two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Minuend. In case of incompatibilities, its configuration would prevail. - @param second Subtrahend. - **/ - public static UnitP Subtraction(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Subtraction, - OperationsOther.GetOperationString(first, second, Operations.Subtraction) - ); - } - - /** - Multiplies two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Multiplicand. In case of incompatibilities, its configuration would prevail. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Multiplies a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Multiplication(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Multiplication, - OperationsOther.GetOperationString(first, second, Operations.Multiplication) - ); - } - - /** - Divides two UnitP variables by giving preference to the configuration of the first operand. - Different unit types will trigger an error. - @param first Dividend. In case of incompatibilities, its configuration would prevail. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides the value of a UnitP variable by a double one. - Eventual errors will be managed as defined in first.ExceptionHandling. - @param first Dividend. - @param second Divisor. - **/ - public static UnitP Division(UnitP first, double second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - /** - Divides a double variable by the value of a UnitP one. - Eventual errors will be managed as defined by the double type. - @param first Multiplicand. - @param second Multiplier. - **/ - public static UnitP Division(double first, UnitP second) - { - return OperationsPublic.PerformUnitOperation - ( - first, second, Operations.Division, - OperationsOther.GetOperationString(first, second, Operations.Division) - ); - } - - @Override - /** - Compares the current instance against another UnitP one. - @param other The other UnitP instance. - **/ - public int compareTo(UnitP other) - { - return - ( - this.BaseTenExponent == other.BaseTenExponent ? - new Double(this.Value * this.UnitPrefix.Factor).compareTo - ( - other.Value * other.UnitPrefix.Factor - ) : - this.BaseTenExponent.compareTo(other.BaseTenExponent) - ); - } - - @Override - /** - Determines whether the current UnitP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((UnitP)obj); - } - - boolean Equals(UnitP other) - { - return - ( - other == null ? false : - Equals.UnitPVarsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this UnitP instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ff/109ea443614c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ff/109ea443614c0017146ede6da4ae5d42 deleted file mode 100644 index 5a1ecf8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ff/109ea443614c0017146ede6da4ae5d42 +++ /dev/null @@ -1,629 +0,0 @@ -package InternalUnitParser.Hardcoding; - -import UnitParser.*; - -import java.util.ArrayList; -import java.util.HashMap; - -/** -Class including the main hardcoded resources used for internal purposes. -In the original C# code, all this is stored in different files in the Keywords/Private folder. -**/ -@SuppressWarnings("serial") -public class HCUnits -{ - /** - Relates the primary string representations (constants in the UnitSymbols class) with the corresponding - unit (element of the Units enum). - **/ - public static HashMap AllUnitSymbols; - - /**Includes all the units with compound (= dividable by default) types which cannot be divided.**/ - public static ArrayList AllNonDividableUnits; - - /**English-system units which are identical in both Imperial and USCS.**/ - public static ArrayList AllImperialAndUSCSUnits; - - public static String Start() - { - AllUnitSymbols = new HashMap() - { - //--- Unitless - { put("unitless", Units.Unitless); } - - //--- Length - { put(UnitSymbols.Metre, Units.Metre); } - { put(UnitSymbols.Centimetre, Units.Centimetre); } - { put(UnitSymbols.AstronomicalUnit, Units.AstronomicalUnit); } - { put(UnitSymbols.Inch, Units.Inch); } - { put(UnitSymbols.Foot, Units.Foot); } - { put(UnitSymbols.Yard, Units.Yard); } - { put(UnitSymbols.Mile, Units.Mile); } - { put(UnitSymbols.NauticalMile, Units.NauticalMile); } - { put(UnitSymbols.Thou, Units.Thou); } - { put(UnitSymbols.Mil, Units.Mil); } - { put(UnitSymbols.Fathom, Units.Fathom); } - { put(UnitSymbols.Rod, Units.Rod); } - { put(UnitSymbols.Perch, Units.Perch); } - { put(UnitSymbols.Pole, Units.Pole); } - { put(UnitSymbols.Chain, Units.Chain); } - { put(UnitSymbols.Furlong, Units.Furlong); } - { put(UnitSymbols.SurveyInch, Units.SurveyInch); } - { put(UnitSymbols.SurveyFoot, Units.SurveyFoot); } - { put(UnitSymbols.SurveyYard, Units.SurveyYard); } - { put(UnitSymbols.SurveyRod, Units.SurveyRod); } - { put(UnitSymbols.SurveyChain, Units.SurveyChain); } - { put(UnitSymbols.SurveyLink, Units.SurveyLink); } - { put(UnitSymbols.SurveyMile, Units.SurveyMile); } - { put(UnitSymbols.SurveyFathom, Units.SurveyFathom); } - { put(UnitSymbols.Link, Units.Link); } - { put(UnitSymbols.Angstrom, Units.Angstrom); } - { put(UnitSymbols.Fermi, Units.Fermi); } - { put(UnitSymbols.LightYear, Units.LightYear); } - { put(UnitSymbols.Parsec, Units.Parsec); } - { put(UnitSymbols.Micron, Units.Micron); } - - //--- Mass - { put(UnitSymbols.Gram, Units.Gram); } - { put(UnitSymbols.MetricTon, Units.MetricTon); } - { put(UnitSymbols.Grain, Units.Grain); } - { put(UnitSymbols.Drachm, Units.Drachm); } - { put(UnitSymbols.Ounce, Units.Ounce); } - { put(UnitSymbols.Pound, Units.Pound); } - { put(UnitSymbols.Stone, Units.Stone); } - { put(UnitSymbols.Slug, Units.Slug); } - { put(UnitSymbols.Quarter, Units.Quarter); } - { put(UnitSymbols.LongQuarter, Units.LongQuarter); } - { put(UnitSymbols.ShortQuarter, Units.ShortQuarter); } - { put(UnitSymbols.Hundredweight, Units.Hundredweight); } - { put(UnitSymbols.LongHundredweight, Units.LongHundredweight); } - { put(UnitSymbols.ShortHundredweight, Units.ShortHundredweight); } - { put(UnitSymbols.Ton, Units.Ton); } - { put(UnitSymbols.LongTon, Units.LongTon); } - { put(UnitSymbols.ShortTon, Units.ShortTon); } - { put(UnitSymbols.Carat, Units.Carat); } - { put(UnitSymbols.Dalton, Units.Dalton); } - { put(UnitSymbols.UnifiedAtomicMassUnit, Units.UnifiedAtomicMassUnit); } - - //--- Time - { put(UnitSymbols.Second, Units.Second); } - { put(UnitSymbols.Minute, Units.Minute); } - { put(UnitSymbols.Hour, Units.Hour); } - { put(UnitSymbols.Day, Units.Day); } - { put(UnitSymbols.Shake, Units.Shake); } - - //--- Area - { put(UnitSymbols.SquareMetre, Units.SquareMetre); } - { put(UnitSymbols.SquareCentimetre, Units.SquareCentimetre); } - { put(UnitSymbols.Are, Units.Are); } - { put(UnitSymbols.SquareFoot, Units.SquareFoot); } - { put(UnitSymbols.SquareInch, Units.SquareInch); } - { put(UnitSymbols.SquareRod, Units.SquareRod); } - { put(UnitSymbols.SquarePerch, Units.SquarePerch); } - { put(UnitSymbols.SquarePole, Units.SquarePole); } - { put(UnitSymbols.Rood, Units.Rood); } - { put(UnitSymbols.Acre, Units.Acre); } - { put(UnitSymbols.SurveyAcre, Units.SurveyAcre); } - { put(UnitSymbols.Barn, Units.Barn); } - - //--- Volume - { put(UnitSymbols.CubicMetre, Units.CubicMetre); } - { put(UnitSymbols.CubicCentimetre, Units.CubicCentimetre); } - { put(UnitSymbols.Litre, Units.Litre); } - { put(UnitSymbols.CubicFoot, Units.CubicFoot); } - { put(UnitSymbols.CubicInch, Units.CubicInch); } - { put(UnitSymbols.FluidOunce, Units.FluidOunce); } - { put(UnitSymbols.ImperialFluidOunce, Units.ImperialFluidOunce); } - { put(UnitSymbols.USCSFluidOunce, Units.USCSFluidOunce); } - { put(UnitSymbols.Gill, Units.Gill); } - { put(UnitSymbols.ImperialGill, Units.ImperialGill); } - { put(UnitSymbols.USCSGill, Units.USCSGill); } - { put(UnitSymbols.Pint, Units.Pint); } - { put(UnitSymbols.ImperialPint, Units.ImperialPint); } - { put(UnitSymbols.LiquidPint, Units.LiquidPint); } - { put(UnitSymbols.DryPint, Units.DryPint); } - { put(UnitSymbols.Quart, Units.Quart); } - { put(UnitSymbols.ImperialQuart, Units.ImperialQuart); } - { put(UnitSymbols.LiquidQuart, Units.LiquidQuart); } - { put(UnitSymbols.DryQuart, Units.DryQuart); } - { put(UnitSymbols.Gallon, Units.Gallon); } - { put(UnitSymbols.ImperialGallon, Units.ImperialGallon); } - { put(UnitSymbols.LiquidGallon, Units.LiquidGallon); } - { put(UnitSymbols.DryGallon, Units.DryGallon); } - - //--- Angle - { put(UnitSymbols.Radian, Units.Radian); } - { put(UnitSymbols.Degree, Units.Degree); } - { put(UnitSymbols.Arcminute, Units.Arcminute); } - { put(UnitSymbols.Arcsecond, Units.Arcsecond); } - { put(UnitSymbols.Revolution, Units.Revolution); } - { put(UnitSymbols.Gradian, Units.Gradian); } - { put(UnitSymbols.Gon, Units.Gon); } - - //--- Information - { put(UnitSymbols.Bit, Units.Bit); } - { put(UnitSymbols.Byte, Units.Byte); } - { put(UnitSymbols.Nibble, Units.Nibble); } - { put(UnitSymbols.Quartet, Units.Quartet); } - { put(UnitSymbols.Octet, Units.Octet); } - - //--- Force - { put(UnitSymbols.Newton, Units.Newton); } - { put(UnitSymbols.Kilopond, Units.Kilopond); } - { put(UnitSymbols.PoundForce, Units.PoundForce); } - { put(UnitSymbols.Kip, Units.Kip); } - { put(UnitSymbols.Poundal, Units.Poundal); } - { put(UnitSymbols.OunceForce, Units.OunceForce); } - { put(UnitSymbols.Dyne, Units.Dyne); } - - //--- Velocity - { put(UnitSymbols.MetrePerSecond, Units.MetrePerSecond); } - { put(UnitSymbols.CentimetrePerSecond, Units.CentimetrePerSecond); } - { put(UnitSymbols.FootPerSecond, Units.FootPerSecond); } - { put(UnitSymbols.InchPerSecond, Units.InchPerSecond); } - { put(UnitSymbols.Knot, Units.Knot); } - { put(UnitSymbols.KilometrePerHour, Units.KilometrePerHour); } - { put(UnitSymbols.MilePerHour, Units.MilePerHour); } - - //--- Acceleration - { put(UnitSymbols.MetrePerSquareSecond, Units.MetrePerSquareSecond); } - { put(UnitSymbols.Gal, Units.Gal); } - { put(UnitSymbols.FootPerSquareSecond, Units.FootPerSquareSecond); } - { put(UnitSymbols.InchPerSquareSecond, Units.InchPerSquareSecond); } - - //--- Energy - { put(UnitSymbols.Joule, Units.Joule); } - { put(UnitSymbols.Electronvolt, Units.Electronvolt); } - { put(UnitSymbols.WattHour, Units.WattHour); } - { put(UnitSymbols.BritishThermalUnit, Units.BritishThermalUnit); } - { put(UnitSymbols.ThermochemicalBritishThermalUnit, Units.ThermochemicalBritishThermalUnit); } - { put(UnitSymbols.Calorie, Units.Calorie); } - { put(UnitSymbols.ThermochemicalCalorie, Units.ThermochemicalCalorie); } - { put(UnitSymbols.FoodCalorie, Units.FoodCalorie); } - { put(UnitSymbols.Erg, Units.Erg); } - { put(UnitSymbols.Therm, Units.Therm); } - { put(UnitSymbols.UKTherm, Units.UKTherm); } - { put(UnitSymbols.USTherm, Units.USTherm); } - - //--- Power - { put(UnitSymbols.Watt, Units.Watt); } - { put(UnitSymbols.ErgPerSecond, Units.ErgPerSecond); } - { put(UnitSymbols.Horsepower, Units.Horsepower); } - { put(UnitSymbols.MetricHorsepower, Units.MetricHorsepower); } - { put(UnitSymbols.BoilerHorsepower, Units.BoilerHorsepower); } - { put(UnitSymbols.ElectricHorsepower, Units.ElectricHorsepower); } - { put(UnitSymbols.TonOfRefrigeration, Units.TonOfRefrigeration); } - - //--- Pressure - { put(UnitSymbols.Pascal, Units.Pascal); } - { put(UnitSymbols.Atmosphere, Units.Atmosphere); } - { put(UnitSymbols.TechnicalAtmosphere, Units.TechnicalAtmosphere); } - { put(UnitSymbols.Bar, Units.Bar); } - { put(UnitSymbols.PoundforcePerSquareInch, Units.PoundforcePerSquareInch); } - { put(UnitSymbols.PoundforcePerSquareFoot, Units.PoundforcePerSquareFoot); } - { put(UnitSymbols.MillimetreOfMercury, Units.MillimetreOfMercury); } - { put(UnitSymbols.InchOfMercury32F, Units.InchOfMercury32F); } - { put(UnitSymbols.InchOfMercury60F, Units.InchOfMercury60F); } - { put(UnitSymbols.Barye, Units.Barye); } - { put(UnitSymbols.Torr, Units.Torr); } - { put(UnitSymbols.KipPerSquareInch, Units.KipPerSquareInch); } - - //--- Frequency - { put(UnitSymbols.Hertz, Units.Hertz); } - { put(UnitSymbols.CyclePerSecond, Units.CyclePerSecond); } - - //--- Electric Charge - { put(UnitSymbols.Coulomb, Units.Coulomb); } - { put(UnitSymbols.AmpereHour, Units.AmpereHour); } - { put(UnitSymbols.Franklin, Units.Franklin); } - { put(UnitSymbols.Statcoulomb, Units.Statcoulomb); } - { put(UnitSymbols.ESUOfCharge, Units.ESUOfCharge); } - { put(UnitSymbols.Abcoulomb, Units.Abcoulomb); } - { put(UnitSymbols.EMUOfCharge, Units.EMUOfCharge); } - - //--- Electric Current - { put(UnitSymbols.Ampere, Units.Ampere); } - { put(UnitSymbols.Statampere, Units.Statampere); } - { put(UnitSymbols.ESUOfCurrent, Units.ESUOfCurrent); } - { put(UnitSymbols.Abampere, Units.Abampere); } - { put(UnitSymbols.EMUOfCurrent, Units.EMUOfCurrent); } - { put(UnitSymbols.Biot, Units.Biot); } - - //--- Electric Voltage - { put(UnitSymbols.Volt, Units.Volt); } - { put(UnitSymbols.Statvolt, Units.Statvolt); } - { put(UnitSymbols.ESUOfElectricPotential, Units.ESUOfElectricPotential); } - { put(UnitSymbols.Abvolt, Units.Abvolt); } - { put(UnitSymbols.EMUOfElectricPotential, Units.EMUOfElectricPotential); } - - //--- Electric Resistance - { put(UnitSymbols.Ohm, Units.Ohm); } - { put(UnitSymbols.Statohm, Units.Statohm); } - { put(UnitSymbols.ESUOfResistance, Units.ESUOfResistance); } - { put(UnitSymbols.Abohm, Units.Abohm); } - { put(UnitSymbols.EMUOfResistance, Units.EMUOfResistance); } - - //--- Electric Resistivity - { put(UnitSymbols.OhmMetre, Units.OhmMetre); } - - //--- Electric Conductance - { put(UnitSymbols.Siemens, Units.Siemens); } - { put(UnitSymbols.Mho, Units.Mho); } - { put(UnitSymbols.Gemmho, Units.Gemmho); } - { put(UnitSymbols.Statsiemens, Units.Statsiemens); } - { put(UnitSymbols.Statmho, Units.Statmho); } - { put(UnitSymbols.Absiemens, Units.Absiemens); } - { put(UnitSymbols.Abmho, Units.Abmho); } - - //--- Electric Conductivity - { put(UnitSymbols.SiemensPerMetre, Units.SiemensPerMetre); } - - //--- Electric Capacitance - { put(UnitSymbols.Farad, Units.Farad); } - { put(UnitSymbols.Statfarad, Units.Statfarad); } - { put(UnitSymbols.ESUOfCapacitance, Units.ESUOfCapacitance); } - { put(UnitSymbols.Abfarad, Units.Abfarad); } - { put(UnitSymbols.EMUOfCapacitance, Units.EMUOfCapacitance); } - - //--- Electric Inductance - { put(UnitSymbols.Henry, Units.Henry); } - { put(UnitSymbols.Stathenry, Units.Stathenry); } - { put(UnitSymbols.ESUOfInductance, Units.ESUOfInductance); } - { put(UnitSymbols.Abhenry, Units.Abhenry); } - { put(UnitSymbols.EMUOfInductance, Units.EMUOfInductance); } - - //--- Electric Dipole Moment - { put(UnitSymbols.CoulombMetre, Units.CoulombMetre); } - { put(UnitSymbols.Debye, Units.Debye); } - - //--- Temperature - { put(UnitSymbols.Kelvin, Units.Kelvin); } - { put(UnitSymbols.DegreeCelsius, Units.DegreeCelsius); } - { put(UnitSymbols.DegreeFahrenheit, Units.DegreeFahrenheit); } - { put(UnitSymbols.DegreeRankine, Units.DegreeRankine); } - - //--- Wavenumber - { put(UnitSymbols.ReciprocalMetre, Units.ReciprocalMetre); } - { put(UnitSymbols.Kayser, Units.Kayser); } - - //--- Viscosity - { put(UnitSymbols.PascalSecond, Units.PascalSecond); } - { put(UnitSymbols.Poise, Units.Poise); } - - //--- Kinematic Viscosity - { put(UnitSymbols.SquareMetrePerSecond, Units.SquareMetrePerSecond); } - { put(UnitSymbols.Stokes, Units.Stokes); } - - //--- Amount of Substance - { put(UnitSymbols.Mole, Units.Mole); } - { put(UnitSymbols.PoundMole, Units.PoundMole); } - - //--- Momentum - { put(UnitSymbols.NewtonSecond, Units.NewtonSecond); } - - //--- Angular Velocity - { put(UnitSymbols.RadianPerSecond, Units.RadianPerSecond); } - { put(UnitSymbols.RevolutionPerMinute, Units.RevolutionPerMinute); } - - //--- Angular Acceleration - { put(UnitSymbols.RadianPerSquareSecond, Units.RadianPerSquareSecond); } - - //--- Angular Momentum - { put(UnitSymbols.JouleSecond, Units.JouleSecond); } - - //--- Moment of Inertia - { put(UnitSymbols.KilogramSquareMetre, Units.KilogramSquareMetre); } - - //--- Solid Angle - { put(UnitSymbols.Steradian, Units.Steradian); } - { put(UnitSymbols.SquareDegree, Units.SquareDegree); } - - //--- Luminous Intensity - { put(UnitSymbols.Candela, Units.Candela); } - - //--- Luminous Flux - { put(UnitSymbols.Lumen, Units.Lumen); } - - //--- Luminous Energy - { put(UnitSymbols.LumenSecond, Units.LumenSecond); } - { put(UnitSymbols.Talbot, Units.Talbot); } - - //--- Luminance - { put(UnitSymbols.CandelaPerSquareMetre, Units.CandelaPerSquareMetre); } - { put(UnitSymbols.Nit, Units.Nit); } - { put(UnitSymbols.Stilb, Units.Stilb); } - { put(UnitSymbols.Lambert, Units.Lambert); } - { put(UnitSymbols.FootLambert, Units.FootLambert); } - - //--- Illuminance - { put(UnitSymbols.Lux, Units.Lux); } - { put(UnitSymbols.Phot, Units.Phot); } - { put(UnitSymbols.FootCandle, Units.FootCandle); } - - //--- Logarithmic - { put(UnitSymbols.Bel, Units.Bel); } - { put(UnitSymbols.Neper, Units.Neper); } - - //--- Magnetic Flux - { put(UnitSymbols.Weber, Units.Weber); } - { put(UnitSymbols.Maxwell, Units.Maxwell); } - - //--- Magnetic Field B - { put(UnitSymbols.Tesla, Units.Tesla); } - { put(UnitSymbols.Gauss, Units.Gauss); } - - //--- Magnetic Field H - { put(UnitSymbols.AmperePerMetre, Units.AmperePerMetre); } - { put(UnitSymbols.Oersted, Units.Oersted); } - - //--- Radioactivity - { put(UnitSymbols.Becquerel, Units.Becquerel); } - { put(UnitSymbols.Curie, Units.Curie); } - { put(UnitSymbols.DisintegrationsPerSecond, Units.DisintegrationsPerSecond); } - { put(UnitSymbols.DisintegrationsPerMinute, Units.DisintegrationsPerMinute); } - { put(UnitSymbols.Rutherford, Units.Rutherford); } - - //--- Absorbed Dose - { put(UnitSymbols.Gray, Units.Gray); } - { put(UnitSymbols.Rad, Units.Rad); } - - //--- Absorbed Dose Rate - { put(UnitSymbols.GrayPerSecond, Units.GrayPerSecond); } - - //--- Equivalent Dose - { put(UnitSymbols.Sievert, Units.Sievert); } - { put(UnitSymbols.REM, Units.REM); } - - //--- Exposure - { put(UnitSymbols.CoulombPerKilogram, Units.CoulombPerKilogram); } - { put(UnitSymbols.Roentgen, Units.Roentgen); } - - //--- Catalytic Activity - { put(UnitSymbols.Katal, Units.Katal); } - - //--- Catalytic Activity Concentration - { put(UnitSymbols.KatalPerCubicMetre, Units.KatalPerCubicMetre); } - - //--- Jerk - { put(UnitSymbols.MetrePerCubicSecond, Units.MetrePerCubicSecond); } - - //--- Mass Flow Rate - { put(UnitSymbols.KilogramPerSecond, Units.KilogramPerSecond); } - - //--- Density - { put(UnitSymbols.KilogramPerCubicMetre, Units.KilogramPerCubicMetre); } - - //--- Area Density - { put(UnitSymbols.KilogramPerSquareMetre, Units.KilogramPerSquareMetre); } - - //--- Energy Density - { put(UnitSymbols.JoulePerCubicMetre, Units.JoulePerCubicMetre); } - - //--- Specific Volume - { put(UnitSymbols.CubicMetrePerKilogram, Units.CubicMetrePerKilogram); } - - //--- Volumetric Flow Rate - { put(UnitSymbols.CubicMetrePerSecond, Units.CubicMetrePerSecond); } - - //--- Surface Tension - { put(UnitSymbols.JoulePerSquareMetre, Units.JoulePerSquareMetre); } - - //--- Specific Weight - { put(UnitSymbols.NewtonPerCubicMetre, Units.NewtonPerCubicMetre); } - - //--- Thermal Conductivity - { put(UnitSymbols.WattPerMetrePerKelvin, Units.WattPerMetrePerKelvin); } - - //--- Thermal Conductance - { put(UnitSymbols.WattPerKelvin, Units.WattPerKelvin); } - - //--- Thermal Resistivity - { put(UnitSymbols.MetreKelvinPerWatt, Units.MetreKelvinPerWatt); } - - //--- Thermal Resistance - { put(UnitSymbols.KelvinPerWatt, Units.KelvinPerWatt); } - - //--- Heat Transfer Coefficient - { put(UnitSymbols.WattPerSquareMetrePerKelvin, Units.WattPerSquareMetrePerKelvin); } - - //--- Heat Flux Density - { put(UnitSymbols.WattPerSquareMetre, Units.WattPerSquareMetre); } - - //--- Entropy - { put(UnitSymbols.JoulePerKelvin, Units.JoulePerKelvin); } - - //--- Electric Field Strength - { put(UnitSymbols.NewtonPerCoulomb, Units.NewtonPerCoulomb); } - { put(UnitSymbols.VoltPerMetre, Units.VoltPerMetre); } - - //--- Linear Electric Charge Density - { put(UnitSymbols.CoulombPerMetre, Units.CoulombPerMetre); } - - //--- Surface Electric Charge Density - { put(UnitSymbols.CoulombPerSquareMetre, Units.CoulombPerSquareMetre); } - - //--- Volume Electric Charge Density - { put(UnitSymbols.CoulombPerCubicMetre, Units.CoulombPerCubicMetre); } - - //--- Current Density - { put(UnitSymbols.AmperePerSquareMetre, Units.AmperePerSquareMetre); } - - //--- Electromagnetic Permittivity - { put(UnitSymbols.FaradPerMetre, Units.FaradPerMetre); } - - //--- Electromagnetic Permeability - { put(UnitSymbols.HenryPerMetre, Units.HenryPerMetre); } - - //--- Molar Energy - { put(UnitSymbols.JoulePerMole, Units.JoulePerMole); } - - //--- Molar Entropy - { put(UnitSymbols.JoulePerMolePerKelvin, Units.JoulePerMolePerKelvin); } - - //--- Molar Volume - { put(UnitSymbols.CubicMetrePerMole, Units.CubicMetrePerMole); } - - //--- Molar Mass - { put(UnitSymbols.KilogramPerMole, Units.KilogramPerMole); } - - //--- Molar Concentration - { put(UnitSymbols.MolePerCubicMetre, Units.MolePerCubicMetre); } - - //--- Molal Concentration - { put(UnitSymbols.MolePerKilogram, Units.MolePerKilogram); } - - //--- Radiant Intensity - { put(UnitSymbols.WattPerSteradian, Units.WattPerSteradian); } - - //--- Radiance - { put(UnitSymbols.WattPerSteradianPerSquareMetre, Units.WattPerSteradianPerSquareMetre); } - - //--- Fuel Economy - { put(UnitSymbols.InverseSquareMetre, Units.InverseSquareMetre); } - { put(UnitSymbols.MilePerGallon, Units.MilePerGallon); } - { put(UnitSymbols.ImperialMilePerGallon, Units.ImperialMilePerGallon); } - { put(UnitSymbols.USCSMilePerGallon, Units.USCSMilePerGallon); } - { put(UnitSymbols.KilometrePerLitre, Units.KilometrePerLitre); } - - //--- Sound Exposure - { put(UnitSymbols.SquarePascalSecond, Units.SquarePascalSecond); } - - //--- Sound Impedance - { put(UnitSymbols.PascalSecondPerCubicMetre, Units.PascalSecondPerCubicMetre); } - - //--- Rotational Stiffness - { put(UnitSymbols.NewtonMetrePerRadian, Units.NewtonMetrePerRadian); } - - //--- Bit Rate - { put(UnitSymbols.BitPerSecond, Units.BitPerSecond); } - - //--- Symbol Rate - { put(UnitSymbols.Baud, Units.Baud); } - }; - - AllNonDividableUnits = new ArrayList() - {{ - //--- Area - add(Units.Are); add(Units.Rood); add(Units.Acre); add(Units.Barn); add(Units.SurveyAcre); - - //--- Volume - add(Units.Litre); add(Units.FluidOunce); add(Units.ImperialFluidOunce); add(Units.USCSFluidOunce); add(Units.Gill); - add(Units.ImperialGill); add(Units.USCSGill); add(Units.Pint); add(Units.ImperialPint); add(Units.LiquidPint); - add(Units.DryPint); add(Units.Quart); add(Units.ImperialQuart); add(Units.LiquidQuart); add(Units.DryQuart); - add(Units.Gallon); add(Units.ImperialGallon); add(Units.LiquidGallon); add(Units.DryGallon); - - //--- Force - add(Units.Kilopond); add(Units.PoundForce); add(Units.Kip); add(Units.OunceForce); - - //--- Energy - add(Units.Electronvolt); add(Units.BritishThermalUnit); add(Units.ThermochemicalBritishThermalUnit); - add(Units.Calorie); add(Units.ThermochemicalCalorie); add(Units.FoodCalorie); add(Units.Therm); add(Units.UKTherm); - add(Units.USTherm); - - //--- Power - add(Units.Horsepower); add(Units.MetricHorsepower); add(Units.BoilerHorsepower); add(Units.ElectricHorsepower); - add(Units.TonOfRefrigeration); - - //--- Pressure - add(Units.Atmosphere); add(Units.TechnicalAtmosphere); add(Units.Bar); add(Units.MillimetreOfMercury); add(Units.InchOfMercury32F); - add(Units.InchOfMercury60F); add(Units.Torr); - - //--- Amount of substance - add(Units.PoundMole); - - //Note that all the electricity/magnetism CGS compounds are considered non-dividable. - //This is because of its multi-system peculiarities and what it entails. - //These are old units where the dividable-compound icing isn't expected to be that important. - //Compounds which might be defined without a direct reliance on electricity/magnetism units are - //dividable. For example, G (= Mx/cm2). - - //--- Electric Charge - add(Units.Franklin); add(Units.Statcoulomb); add(Units.ESUOfCharge); add(Units.Abcoulomb); add(Units.EMUOfCharge); - - //--- Electric Voltage - add(Units.ESUOfElectricPotential); add(Units.Statvolt); add(Units.EMUOfElectricPotential); add(Units.Abvolt); - - //--- Electric Resistance - add(Units.Statohm); add(Units.ESUOfResistance); add(Units.Abohm); add(Units.EMUOfResistance); - - //--- Electric Conductance - add(Units.Gemmho); add(Units.Statsiemens); add(Units.Statmho); add(Units.Absiemens); add(Units.Abmho); - - //--- Electric Capacitance - add(Units.Statfarad); add(Units.ESUOfCapacitance); add(Units.Abfarad); add(Units.EMUOfCapacitance); - - //--- Electric Inductance - add(Units.Stathenry); add(Units.ESUOfInductance); add(Units.Abhenry); add(Units.EMUOfInductance); - - //--- Electric Dipole Moment - add(Units.Debye); - - //--- Luminance - add(Units.Lambert); add(Units.FootLambert); - - //--- Magnetic Flux - add(Units.Maxwell); - - //--- Magnetic Field H - add(Units.Oersted); - - //--- Absorbed Dose - add(Units.Rad); - - //--- Equivalent Dose - add(Units.REM); - - //--- Exposure - add(Units.Roentgen); - }}; - - AllImperialAndUSCSUnits = new ArrayList() - {{ - //--- Length - add(Units.Inch); add(Units.Foot); add(Units.Yard); add(Units.Mile); add(Units.Thou); - add(Units.Mil); add(Units.Fathom); add(Units.Rod); add(Units.Perch); add(Units.Pole); - add(Units.Chain); add(Units.Furlong); add(Units.Link); - - //--- Mass - add(Units.Grain); add(Units.Drachm); add(Units.Ounce); add(Units.Pound); add(Units.Stone); - add(Units.Slug); - - //--- Area - add(Units.SquareInch); add(Units.SquareFoot); add(Units.SquareRod); add(Units.SquarePerch); - add(Units.SquarePole); add(Units.Rood); add(Units.Acre); - - //--- Volume - add(Units.CubicInch); add(Units.CubicFoot); - - //--- Force - add(Units.PoundForce); add(Units.Poundal); add(Units.OunceForce); - - //--- Velocity - add(Units.FootPerSecond); add(Units.InchPerSecond); add(Units.MilePerHour); - - //--- Acceleration - add(Units.FootPerSquareSecond); add(Units.InchPerSquareSecond); - - //--- Energy - add(Units.BritishThermalUnit); add(Units.ThermochemicalBritishThermalUnit); - - //--- Power - add(Units.Horsepower); - - //--- Pressure - add(Units.PoundforcePerSquareInch); add(Units.PoundforcePerSquareFoot); - - //--- Temperature - add(Units.DegreeFahrenheit); add(Units.DegreeRankine); - - //--- Luminance - add(Units.FootLambert); - - //--- Illuminance - add(Units.FootCandle); - }}; - - - return ""; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ff/70b27f4b644c0017146ede6da4ae5d42 b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ff/70b27f4b644c0017146ede6da4ae5d42 deleted file mode 100644 index 6c99db0..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ff/70b27f4b644c0017146ede6da4ae5d42 +++ /dev/null @@ -1,436 +0,0 @@ -package Parts; - -import InternalUnitParser.CSharpAdaptation.CSharpOther; -import InternalUnitParser.CSharpAdaptation.Linq; -import UnitParser.*; - -import java.util.Scanner; - -public class UnitParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- UnitParser --------------"); - System.out.println(); - - //------ The base class is UnitP. There are multiple ways to instantiate a UnitP variable. - PrintSampleItem("Inst1", new UnitP("1 N")); //Unit symbol. Case does matter. - PrintSampleItem("Inst2", new UnitP(1.0, UnitSymbols.Newton)); - PrintSampleItem("Inst3", new UnitP(1.0, "nEwTon")); //Unit secondary String representation. Case doesn't matter. - PrintSampleItem("Inst4", new UnitP(Units.Newton)); //Value assumed to be 1. - PrintSampleItem("Inst5", new UnitP()); //Value and unit assumed to be 1 and unitless, respectively. - - - //--- All the public classes support (un)equality comparisons accounting for their more relevant variables. - if - ( - new UnitP("1 N").equals(new UnitP(1.0, UnitSymbols.Newton)) && - new UnitP(1.0, UnitSymbols.Newton).equals(new UnitP(1.0, "nEwTon")) && - new UnitP(1.0, "nEwTon").equals(new UnitP(Units.Newton)) - ) - { - //This condition is true. - } - - //------ UnitP variables can be seen as abstract concepts including many specific types. - - //--- Same type variables can be added/subtracted. - PrintSampleItem("Add1", UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, UnitSymbols.Newton))); //Both variables have the same type (force). - - //--- Different type variables can be multiplied/divided, but only when the resulting output belongs to a supported type. - PrintSampleItem("Mult1", UnitP.Multiplication(new UnitP("1 N"), new UnitP("m"))); //N*m = J, what is a supported type (energy). - - //--- Any operation outputting unsupported types triggers an error. - PrintSampleItem("Mult2", UnitP.Multiplication(UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")), new UnitP("1 m"))); //N*m2 doesn't match any valid type. - - - //------ Multiplication/division with decimal/double values is also supported. - - PrintSampleItem("Mult3", UnitP.Multiplication(new UnitP("1 N"), 1.23456)); //Multiplication involving UnitP and double variables. - PrintSampleItem("Div1", UnitP.Division(new UnitP("1 N"), 7.891011)); //Division involving UnitP and decimal variables. - - //--- Dividing a number by a UnitP variable does affect the given unit. - try - { - PrintSampleItem("Div2", UnitP.Division(7.891011, new UnitP("1 N"))); - } - catch(Exception e) - { - //Error because 1/N doesn't represent a supported type. - //The reasons for the exception are explained below. - System.out.println("Div2 - Caught Exception."); - } - - - //------ Compounds, unit parts and individual units. - - PrintSampleItem("Ind1", new UnitP("1 sec")); //s, a valid SI time unit. It is an individual unit (i.e., 1 single unit part whose exponent is 1). - PrintSampleItem("Comp1", new UnitP("1 m/s")); //m/s, a valid SI velocity unit. It is a compound (i.e., various parts or one with a different-than-1 exponent). - PrintSampleItem("Comp2", new UnitP("1 N")); //N, a valid SI force unit. It is a compound with an official name. - - //--- Compounds can be formed through String parsing or arithmetic operations. - PrintSampleItem("Comp3", UnitP.Division(new UnitP("1 m"), new UnitP("s"))); //m/s, a valid SI velocity unit, created by dividing two UnitP variables. - PrintSampleItem("Comp4", new UnitP("kg*m/s2")); //N (= kg*m/s2), a valid SI force unit, created via String parsing. - if (new UnitP("1 m/sec").equals(UnitP.Division(new UnitP("1 m"), new UnitP("s"))) && new UnitP("1 N").equals(new UnitP("1 kg*m/s2"))) - { - //This condition is true. - } - - //--- It is recommendable to create compounds via strings rather than operations. - PrintSampleItem("Comp5", UnitP.Division(new UnitP("1 m"), new UnitP("1 s2"))); //Error because s2 doesn't represent a valid type (type check for each UnitP variable). - PrintSampleItem("Comp6", new UnitP("m/s2")); //m/s2, a valid SI acceleration unit (one type check after all the unit operations/simplifications were performed). - - //--- The unit parts are automatically populated when instantiating a valid UnitP variable. - if (Linq.FirstOrDefault(new UnitP("1 N").UnitParts, x -> !new UnitP("1 kg*m/s2").UnitParts.contains(x), null) == null) - { - System.out.println("Condition 3 true"); - //This condition is true. - } - - //--- When various units have the same constituent parts, the String-based recognition might not match the input unit. - PrintSampleItem("Comp7", new UnitP("V/m")); //Understood as NewtonPerCoulomb. Although V/m is a valid SI electric field strength unit, N/C has the same parts and is the default unit under these conditions. - PrintSampleItem("Comp8", new UnitP(Units.VoltPerMetre)); //Understood as VoltPerMetre. There is no String parsing/unit-part analysis and, consequently, no possible confusion. - - //------ Format of input String units. - - //--- UnitP constructors without numeric inputs expect strings formed by a number (it might be missing) and a unit. - PrintSampleItem("Str1", new UnitP("10 m")); //10 metre (length). - PrintSampleItem("Str2", new UnitP("1m")); //1 metre (length). Since UnitParser.dll v.1.0.6301.23655, there is no need to include a blank space between value and unit. - PrintSampleItem("Str3", new UnitP("m")); //1 metre (length). - - //--- Multi-part strings are expected to be formed by units, multiplication/division symbols and integer exponents. - PrintSampleItem("Str4", new UnitP("1 J/s")); //1 joule per second (power unit). - PrintSampleItem("Str5", new UnitP("1 Jxs")); //1 joule second (angular momentum). - PrintSampleItem("Str6", new UnitP("1 J⋅s2")); //1 kilogram square metre (moment of inertia). - PrintSampleItem("Str7", new UnitP("J÷s-2")); //1 kilogram square metre (moment of inertia). - - //--- Only one division sign is expected. It separates the numerator and denominator parts. - PrintSampleItem("Str8", new UnitP("1 J*J/s*J2*J-1*s*s-1")); //1 watt (power). - PrintSampleItem("Str9", new UnitP("J*J/(s*J2*s)*J*s")); //Error. It is understood as J*J/(s*J2*s*J*s). - - //--- Not-supported-but-commonly-used characters are plainly ignored. - PrintSampleItem("Str10", new UnitP(1.0, "ft.")); //1 foot (length). - PrintSampleItem("Str11", new UnitP(1.0, "ft^2")); //1 square foot (area). - PrintSampleItem("Str12", new UnitP(1.0, "ft*(ft*ft)")); //1 cubic foot (volume). - - //--- Ideally, no blank spaces should be included. The parser can deal with them anyway. - PrintSampleItem("Str13", new UnitP(1.0, "AU/min")); //1 astronomical unit per minute (velocity). - PrintSampleItem("Str14", new UnitP(1.0, "A U/ min")); //1 astronomical unit per minute (velocity). - - - //------ Format of input String numbers. - - //--- The used culture is always CultureInfo.InvariantCulture (e.g., "." as decimal separator). - PrintSampleItem("StrNum1", new UnitP("1.1 m")); //Always 1.1 m, independently upon the applicable culture. - PrintSampleItem("StrNum2", new UnitP("1,1 s")); //Always 11 s, independently upon the applicable culture. - - //--- The differences between double/decimal types are managed internally. - PrintSampleItem("StrNum3", new UnitP("1.0000000000000001 ft")); //1.0000000000000001 ft. - PrintSampleItem("StrNum4", new UnitP("1000000000000000000000000000000000000000000000000000000000000 mi")); //1000000*10^54 mi. - - //--- It is also possible to input beyond-double numbers via strings. The exponential format follows the .NET rules. - PrintSampleItem("StrNum5", new UnitP("9999.99999E1000")); //999999.99*10^998 unitless. - PrintSampleItem("StrNum6", new UnitP("1234E1.5")); //Error. Equivalently to what happens with .NET numeric parsing, only integer exponents are supported. - - - //------ Errors and exceptions. - - //--- All the error information is stored under UnitPVariable.Error. - if (new UnitP("1 m/s").Error.Type == UnitP.ErrorTypes.None) - { - //This condition is true. - } - if (new UnitP("wrong").Error.Type != UnitP.ErrorTypes.None) - { - //This condition is true. - } - - //--- By default, errors don't trigger exceptions. - PrintSampleItem("Err1", new UnitP("wrong")); //No exception is triggered. - - //--- The default behaviour can be modified when instantiating the variable. - try - { - PrintSampleItem("Err2", new UnitP("wrong", UnitP.ExceptionHandlingTypes.AlwaysTriggerException)); - } - catch(Exception e) - { - //An exception is triggered. - System.out.println("Err2 - Caught Exception."); - } - - //--- In case of incompatibility, the configuration of the first operand is applied. - PrintSampleItem - ( - "Err3", //No exception is triggered. - UnitP.Multiplication - ( - new UnitP("wrong"), new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException) - ) - ); - - try - { - PrintSampleItem - ( - "Err4", //An exception is triggered. - UnitP.Multiplication - ( - new UnitP("1 m", UnitP.ExceptionHandlingTypes.AlwaysTriggerException), new UnitP("wrong") - ) - ); - } - catch(Exception e) - { - System.out.println("Err4 - Caught Exception."); - } - - //--- When the first operand is a number, an exception is always triggered. - try - { - //An exception is triggered. - PrintSampleItem("Err5", UnitP.Multiplication(5.0, new UnitP("wrong"))); - } - catch(Exception e) - { - System.out.println("Err5 - Caught Exception."); - } - - - //------ Unit prefixes. - - //--- Two types of prefixes are supported: SI and binary. - PrintSampleItem("Pref1", new UnitP(1.0, "km")); //SI prefix kilo + metre. - PrintSampleItem("Pref2", new UnitP("1 Kibit")); //Binary prefix Kibi + bit. - - //--- All the prefix-related information is stored under UnitPVariable.UnitPrefix. - if (new UnitP(1.0, "km").UnitPrefix == new UnitP(1.0, "ks").UnitPrefix) - { - //This condition is true. - } - - //--- Prefixes are automatically updated/simplified in any operation. - PrintSampleItem("Pref3", new UnitP("1 kJ")); //1 kJ. - PrintSampleItem("Pref4", new UnitP("555 mJ")); //555 mJ. - PrintSampleItem("Pref5", new UnitP("0.00000001 MJ")); //0.01 J. - PrintSampleItem - ( - "Pref6", UnitP.Addition - ( - UnitP.Addition(new UnitP("1 kJ"), new UnitP("555 mJ")), new UnitP("0.00000001 MJ") - ) - ); //1.000565 kJ. - - //--- Prefix symbols are case sensitive, but String representations are not. - PrintSampleItem("Pref7", new UnitP(1.0, "Km")); //Error. - PrintSampleItem("Pref8", new UnitP(1.0, "mEGam")); //SI prefix mega + metre. - - //--- By default, prefixes can only be used with units which officially/commonly support them. - PrintSampleItem("Pref9", new UnitP("1 Mft")); //Error because the unit foot doesn't support SI prefixes. - PrintSampleItem("Pref10", new UnitP("Eim")); //Error because the unit metre doesn't support binary prefixes. - - //--- The default behaviour can be modified when instantiating the variable. - PrintSampleItem("Pref11", new UnitP("Mft", PrefixUsageTypes.AllUnits)); //SI prefix mega + foot. - PrintSampleItem("Pref12", new UnitP("1 Eim", PrefixUsageTypes.AllUnits)); //Binary prefix exbi + metre. - - //--- Same rules apply to officially-named compounds. Non-named compounds recognise prefixes, but don't use them. - PrintSampleItem("Pref13", new UnitP("1 GN")); //SI prefix giga + newton. - PrintSampleItem("Pref14", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond)); //1000000*10^3 m/s. - - //--- In certain situations, PrefixUsageTypes.AllUnits doesn't allow to use prefixes. - PrintSampleItem("Pref15", new UnitP(1.0, SIPrefixSymbols.Giga + Units.MetrePerSecond, PrefixUsageTypes.AllUnits)); //Compounds with no official name don't support prefixes. - PrintSampleItem("Pref16", new UnitP("100000000000 unitless", PrefixUsageTypes.AllUnits)); //Unitless variables don't support prefixes. - - //--- The unit parts can also have prefixes, which might be compensated with the main prefix. - PrintSampleItem("Pref17", new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton)); //kN. SI prefix kilo directly affecting the unit newton. - PrintSampleItem("Pref18", new UnitP("1 Mg*m/s2")); //kN. SI prefix kilo indirectly affecting newton, via one of its constituent parts (kilo-kg = Mg). - if (new UnitP(1.0, SIPrefixSymbols.Kilo + UnitSymbols.Newton) == new UnitP("1 Mg*m/s2")) - { - //This condition is true. - //Note that both UnitP variables being equal implies identical prefixes. - } - - - //------ Systems of units. - - //--- The system is automatically determined at variable instantiation. Each unit can belong to just one system. - PrintSampleItem("Sys1", new UnitP(Units.MetrePerSquareSecond)); //SI acceleration unit (m/s2). - PrintSampleItem("Sys2", new UnitP("cm/s2")); //CGS acceleration unit (Gal). - PrintSampleItem("Sys3", new UnitP(1.0, UnitSymbols.Rod + "/h2")); //Imperial acceleration unit (rd/h2). - PrintSampleItem("Sys4", new UnitP(1.0, UnitSymbols.SurveyRod + "/s2")); //USCS acceleration unit (surrd/s2). - PrintSampleItem("Sys5", new UnitP(1.0, "AU/min2")); //Acceleration unit not belonging to any system (AU/min2). - - - //------ Automatic unit conversions. - - //--- Automatic conversions (to the system of the first operand) happen in operations between a big proportion of different-system units. - PrintSampleItem("Conv1", UnitP.Multiplication(new UnitP(1.0, Units.Metre), new UnitP("1 ft"))); //After converting ft to metre, SI area unit m2. - PrintSampleItem("Conv2", UnitP.Addition(new UnitP(Units.PoundForce), new UnitP(5.0, "N"))); //After converting N to lbf, Imperial/USCS force unit lbf. - - //--- Same rules apply to compounds whose unit parts belong to different systems. - PrintSampleItem("Conv3", new UnitP(1.0, "m*lb/s2")); //After converting lb to kg, SI force unit N. - PrintSampleItem("Conv4", new UnitP(1.0, "surin3/in")); //After converting in to surin, USCS area unit surin2. - - - //------ Numeric support. - - //--- UnitP variables support two different numeric types: decimal and double. - PrintSampleItem("Num1", new UnitP(1.23456, "m")); //The UnitP constructor overloads only support decimal type. - PrintSampleItem("Num2", UnitP.Multiplication(new UnitP("ft"), 7.891011)); //Decimal variables can be used in multiplications/divisions. - PrintSampleItem("Num3", UnitP.Multiplication(new UnitP("s"), 1213141516.0)); //Double variables can be used in multiplications/divisions. - - //--- All the numeric inputs are converted into decimal type. UnitPVariable.BaseTenExponent avoids eventual type-conversion overflow problems. - PrintSampleItem - ( - //UnitP variable with a Numeric value notably above decimal.MaxValue. - "Num4", UnitP.Division - ( - new UnitP(9999999999999999.0, "YAU2", PrefixUsageTypes.AllUnits), - new UnitP("0.000000000000001 yf", PrefixUsageTypes.AllUnits) - ) - ); - PrintSampleItem - ( - //UnitP variable with a Numeric value notably below decimal.MinValue. - "Num5", UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ) - ); - - - //------ No unit, unitless & unnamed units. - - //--- No unit (Units.None). - PrintSampleItem("No1", new UnitP(1.0, Units.None)); //Units.None cannot be used as an input. - PrintSampleItem("No2", new UnitP("1 wrong")); //Units.None is the unit associated with all the errors. - - //--- Unitless (Units.Unitless). - PrintSampleItem("No3", new UnitP(1.0, Units.Unitless)); //Units.Unitless can be used as an input. - PrintSampleItem("No4", new UnitP("5e1234")); //Units.Unitless is the unit for purely-numeric calculations. - PrintSampleItem("No5", UnitP.Division(new UnitP("5 km"), new UnitP(1.0, Units.Unitless))); //Units.Unitless can be used together with other valid units without triggering an error. - PrintSampleItem("No6", new UnitP("1 ft/m")); //Units.Unitless is associated with the output of operations where all the units cancel each other (with or without automatic conversions). - - //--- Unnamed units (Units.Valid[system]Unit). - PrintSampleItem("No7", new UnitP("yd/s")); //All the parsed compounds not matching any named unit are automatically included in this category. - PrintSampleItem("No8", new UnitP(1.0, Units.ValidCGSUnit)); //Error. Unnamed units cannot be used as inputs. - - //------ Public functions. - - //--- All the functions have static/UnitP and non-static/UnitPVariable versions. - System.out.println - ( - "Func1 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", UnitP.GetStringsForUnit(Units.Abampere, true) //Static method returning all the String representations associated with the input unit. - ) - ); - - System.out.println - ( - "Func2 - " + Units.Abampere.toString() + " -> " + CSharpOther.StringJoin - ( - ",", new UnitP(1.0, Units.Abampere).GetStringsForCurrentUnit(true) //Non-static method returning all the String representations associated with the current unit. - ) - ); - - //--- The most relevant function is the one performing unit conversions. - PrintSampleItem("Func3", UnitP.ConvertTo(new UnitP("1 m"), Units.Foot)); //Static version of the unit conversion method. - PrintSampleItem("Func4", new UnitP("1 m/s").ConvertCurrentUnitTo("ft/h")); //Non-static version of the unit conversion method. - PrintSampleItem("Func5", new UnitP("1 m").ConvertCurrentUnitTo(Units.Gram)); //Error. No conversion is possible between different-type units. - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- NumberParser. - //PrintSampleItem("NP1", new UnitP(new Number(123m, 5), Units.Abampere)); //12.3 MabA. - //PrintSampleItem("NP2", new UnitP(new NumberD(0.000000000001, -5), "Gs")); //0.01 µs. - //PrintSampleItem("NP3", new UnitP(new NumberP("Error"), "m/s")); //Error. - - - //------------------------------------------------------------- - - - System.out.println(); - System.out.println(); - System.out.println("Do you want to print all the named units? Y/N"); - - - Scanner scanner = new Scanner(System.in); - String input = scanner.nextLine(); - if (input.toLowerCase().trim().equals("y")) - { - //--- Printing all the supported named units out. - PrintAllNamedUnits(); - } - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - scanner.next(); - scanner.close(); - } - - static void PrintSampleItem(String sampleId, UnitP unitP) - { - System.out.println - ( - sampleId + " - " + - ( - unitP.Error.Type != UnitP.ErrorTypes.None ? - "Error. " + unitP.Error.Message : - unitP.ValueAndUnitString + " (" + - unitP.Unit.toString() + ", " + - unitP.UnitType.toString() + ", " + - unitP.UnitSystem.toString() + ")." - ) - ); - } - - //This method prints the main String representations and some basic information for all the named units. - //In any case, note that UnitParser supports a wide range of variations which aren't referred here. - //Examples: plurals of String representation other than symbols or ignoring certain invalid characters - //(e.g., blank spaces or conventionally-used characters like "^"). - //Additionally, bear in mind that these are just the members of the Units enum, a small fraction of - //all the units supported by UnitParser. Any unit belonging to a supported type (UnitTypes enum) which - //is formed by the combination of one or more named units (Units enum) is also supported. For example, - //the named unit Units.Foot can be part of many other unnamed units like ft/h (velocity), rood*ft (volume) - //or tn*ft/s2 (force). - static void PrintAllNamedUnits() - { - for (Units unit: Units.values()) - { - if (unit == Units.None || unit == Units.Unitless) continue; - - UnitTypes type = UnitP.GetUnitType(unit); - UnitSystems system = UnitP.GetUnitSystem(unit); - - if (type == UnitTypes.None) continue; - - System.out.println("Unit: " + unit.toString()); - System.out.println("Type: " + type.toString()); - System.out.println("System: " + system.toString()); - - String representations = ""; - for (String representation: UnitP.GetStringsForUnit(unit, true)) - { - if (representations != "") representations += ", "; - representations += representation; - } - - System.out.println("Representations: " + representations); - System.out.println(); - } - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ff/8068164de74c00171118892245944c7f b/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ff/8068164de74c00171118892245944c7f deleted file mode 100644 index be3eaf3..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.history/ff/8068164de74c00171118892245944c7f +++ /dev/null @@ -1,254 +0,0 @@ -package InternalUnitParser.CSharpAdaptation; - -import InternalUnitParser.Classes.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -//Class including Java custom versions for all the System.Linq methods used in the original C# code. -@SuppressWarnings({ "serial", "rawtypes", "unchecked" }) -public class Linq -{ - public static int Count(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return 0; - - return (int)input.stream().filter(filter).count(); - } - - public static ArrayList Distinct(ArrayList input) - { - if (input == null || input.size() < 2) return input; - - return (ArrayList) input.stream().distinct().collect - ( - Collectors.toList() - ); - } - - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return input; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList SelectDict(HashMap input, Function, Z> filter) - { - if (input == null || input.entrySet() == null || filter == null) - { - return new ArrayList(); - } - - return (ArrayList)input.entrySet().stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList TakeWhile(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null || filter == null) return input; - - ArrayList output = new ArrayList(); - ArrayList input2 = Where(input, filter); - - for (X item: input) - { - if (!input2.contains(item)) break; - - output.add(item); - } - - if (output.size() < 1) - { - output.add(defaultVal); - } - - return output; - } - - public static Map.Entry Max(HashMap input, Comparator> comparator) - { - if (input == null || input.entrySet() == null || input.size() < 2) - { - return FirstOrDefaultDict(input, null); - } - - return FirstOrDefaultDict - ( - OrderByDescending(new ArrayList(input.entrySet()), comparator), null - ); - } - - public static ArrayList GroupByJustCountAndOrderByDescending(ArrayList input, Comparator comparator) - { - if (input == null || comparator == null) return input; - - return (ArrayList)OrderByDescending - ( - (ArrayList)GroupByJustCount(input, comparator), new Comparator() - { - public int compare(XAndIntegerClass first, XAndIntegerClass second) - { - return first.Count.compareTo(second.Count); - } - } - ) - .stream().map(x -> x.Input).collect(Collectors.toList()); - } - - static ArrayList GroupByJustCount(ArrayList input, Comparator comparator) - { - ArrayList output = new ArrayList() - {{ - add(new XAndIntegerClass(input.get(0), 1)); - }}; - if (input == null || input.size() < 2) return output; - - ArrayList sorted = OrderBy(input, comparator); - - X last = sorted.get(0); - Integer count = 1; - - for (int i = 1; i < sorted.size(); i++) - { - X current = sorted.get(i); - - if (current == last) count++; - else - { - output.add(new XAndIntegerClass(current, count)); - count = 1; - last = current; - } - } - - if (count > 1) - { - output.add(new XAndIntegerClass(last, count)); - } - - return output; - } - - public static ArrayList OrderBy(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, true); - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), defaultVal - ); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - static X GetFirst(ArrayList input, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Map.Entry defaultVal) - { - return FirstOrDefaultDict(input, null, defaultVal); - } - - public static Map.Entry FirstOrDefaultDict(HashMap input, Predicate> filter, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - return GetFirstDict - ( - new HashMap(WhereDict(input, filter)), defaultVal - ); - } - - public static HashMap WhereDict(HashMap input, Predicate> filter) - { - if (input == null || input.keySet() == null || filter == null) return input; - - try - { - return (HashMap)input.entrySet().stream().filter(filter).collect - ( - Collectors.toMap(x -> x.getKey(), x -> x.getValue()) - ); - } - catch(Exception e) { } - - return input; - } - - static Map.Entry GetFirstDict(HashMap input, Map.Entry defaultVal) - { - if (input == null || input.entrySet() == null) return defaultVal; - - try - { - for (Map.Entry entry : input.entrySet()) - { - return entry; - } - } - catch (Exception e) { } - - return defaultVal; - } -} diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/Test/.indexes/e4/c0/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/Test/.indexes/e4/c0/history.index deleted file mode 100644 index 171ab38..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/Test/.indexes/e4/c0/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/Test/.indexes/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/Test/.indexes/history.index deleted file mode 100644 index 37784df..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/Test/.indexes/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/Test/org.eclipse.jdt.core/state.dat b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/Test/org.eclipse.jdt.core/state.dat deleted file mode 100644 index 16925a3..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/Test/org.eclipse.jdt.core/state.dat and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/44/1d/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/44/1d/history.index deleted file mode 100644 index d41fd38..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/44/1d/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/44/de/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/44/de/history.index deleted file mode 100644 index c182a18..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/44/de/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/35/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/35/history.index deleted file mode 100644 index 1e93afb..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/35/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/6e/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/6e/history.index deleted file mode 100644 index f3cb260..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/6e/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/93/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/93/history.index deleted file mode 100644 index 670dab1..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/93/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/c/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/c/history.index deleted file mode 100644 index 1f09120..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/c/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/da/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/da/history.index deleted file mode 100644 index f982840..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/da/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/fa/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/fa/history.index deleted file mode 100644 index 371b766..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/d8/80/fa/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/history.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/history.index deleted file mode 100644 index d04300a..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/history.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/properties.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/properties.index deleted file mode 100644 index 1cc40e5..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.indexes/properties.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.location b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.location deleted file mode 100644 index 32d7410..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.location and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.markers b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.markers deleted file mode 100644 index 35c205e..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/.markers and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/org.eclipse.jdt.core/state.dat b/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/org.eclipse.jdt.core/state.dat deleted file mode 100644 index f75b555..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.projects/UnitParser/org.eclipse.jdt.core/state.dat and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/history.version b/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/history.version deleted file mode 100644 index 25cb955..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/history.version +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.index b/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.index deleted file mode 100644 index ec4ff10..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.version b/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.version deleted file mode 100644 index 6b2aaa7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/.indexes/properties.version +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/73.tree b/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/73.tree deleted file mode 100644 index 681a6ef..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.root/73.tree and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.resources/.safetable/org.eclipse.core.resources b/all_code/.metadata/.plugins/org.eclipse.core.resources/.safetable/org.eclipse.core.resources deleted file mode 100644 index 4c37863..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.core.resources/.safetable/org.eclipse.core.resources and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.net.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.net.prefs deleted file mode 100644 index 2774420..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.net.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.core.net.hasMigrated=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.resources.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index a7fb09f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,3 +0,0 @@ -description.autobuilding=false -eclipse.preferences.version=1 -version=1 diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.debug.core.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.debug.core.prefs deleted file mode 100644 index de224d8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.debug.core.prefs +++ /dev/null @@ -1,3 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.debug.core.PREF_BREAKPOINT_MANAGER_ENABLED_STATE=false -org.eclipse.debug.core.USE_STEP_FILTERS=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.debug.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.debug.ui.prefs deleted file mode 100644 index f09a724..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.debug.ui.prefs +++ /dev/null @@ -1,7 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.debug.ui.BreakpointView+org.eclipse.debug.ui.actions.SkipAllBreakpoints=true -org.eclipse.debug.ui.PREF_LAUNCH_PERSPECTIVES=\r\n\r\n -org.eclipse.debug.ui.switch_perspective_on_suspend=never -pref_state_memento.org.eclipse.debug.ui.DebugVieworg.eclipse.debug.ui.DebugView=\r\n -preferredDetailPanes=DefaultDetailPane\:DefaultDetailPane| -preferredTargets=default\:default| diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.epp.logging.aeri.ide.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.epp.logging.aeri.ide.prefs deleted file mode 100644 index c186df8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.epp.logging.aeri.ide.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -resetSendMode=KEEP -resetSendModeOn=0 -sendMode=NOTIFY diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.core.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index ac9c3bb..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,310 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.codeComplete.visibilityCheck=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.8 -org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647 -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0 -org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_type_arguments=0 -org.eclipse.jdt.core.formatter.alignment_for_type_parameters=0 -org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=next_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=next_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=next_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=next_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=next_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=next_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=next_line -org.eclipse.jdt.core.formatter.brace_position_for_lambda_body=next_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=next_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=next_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=next_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false -org.eclipse.jdt.core.formatter.comment.format_block_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true -org.eclipse.jdt.core.formatter.comment.format_line_comments=true -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true -org.eclipse.jdt.core.formatter.comment.indent_root_tags=true -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert -org.eclipse.jdt.core.formatter.comment.line_length=80 -org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true -org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true -org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off -org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.join_lines_in_comments=true -org.eclipse.jdt.core.formatter.join_wrapped_lines=true -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=120 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation=common_lines -org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause=common_lines -org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration=common_lines -org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment=common_lines -org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement=common_lines -org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration=common_lines -org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration=common_lines -org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation=common_lines -org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement=common_lines -org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause=common_lines -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_on_off_tags=false -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true -org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true -org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true -org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.debug.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.debug.ui.prefs deleted file mode 100644 index 536506b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.debug.ui.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.debug.ui.VariableView.org.eclipse.jdt.debug.ui.show_null_entries=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.launching.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.launching.prefs deleted file mode 100644 index 6b42527..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.launching.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.launching.PREF_VM_XML=\r\n\r\n\r\n\r\n\r\n\r\n diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index be45f3c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,24 +0,0 @@ -command=C\:\\Program Files\\Java\\jdk1.8.0_91\\bin\\javadoc.exe -content_assist_disabled_computers=org.eclipse.jdt.ui.textProposalCategory\u0000org.eclipse.recommenders.calls.rcp.proposalCategory.templates\u0000org.eclipse.mylyn.java.ui.javaAllProposalCategory\u0000org.eclipse.jdt.ui.javaAllProposalCategory\u0000org.eclipse.jdt.ui.javaTypeProposalCategory\u0000org.eclipse.jdt.ui.javaNoTypeProposalCategory\u0000org.eclipse.recommenders.chain.rcp.proposalCategory.chain\u0000 -content_assist_lru_history= -content_assist_number_of_computers=19 -content_assist_proposals_background=255,255,255 -content_assist_proposals_foreground=0,0,0 -eclipse.preferences.version=1 -fontPropagated=true -formatter_profile=_Proper braces -formatter_settings_version=12 -org.eclipse.jdt.ui.editor.tab.width= -org.eclipse.jdt.ui.formatterprofiles=\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n -org.eclipse.jdt.ui.formatterprofiles.version=12 -org.eclipse.jdt.ui.javadoclocations.migrated=true -org.eclipse.jdt.ui.text.code_templates_migrated=true -org.eclipse.jdt.ui.text.custom_code_templates= -org.eclipse.jdt.ui.text.custom_templates= -org.eclipse.jdt.ui.text.templates_migrated=true -org.eclipse.jface.textfont=1|Consolas|10.0|0|WINDOWS|1|0|0|0|0|0|0|0|0|1|0|0|0|0|Consolas; -proposalOrderMigrated=true -spelling_locale_initialized=true -tabWidthPropagated=true -useAnnotationsPrefPage=true -useQuickDiffPrefPage=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.m2e.discovery.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.m2e.discovery.prefs deleted file mode 100644 index 67b1d96..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.m2e.discovery.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.discovery.pref.projects= diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.context.core.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.context.core.prefs deleted file mode 100644 index 43e97e4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.context.core.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -mylyn.attention.migrated=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.java.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.java.ui.prefs deleted file mode 100644 index 2a6fe50..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.java.ui.prefs +++ /dev/null @@ -1,3 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.mylyn.java.ui.run.count.3_10_0=1 -org.eclipse.mylyn.java.ui.run.count.3_1_0=1 diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.monitor.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.monitor.ui.prefs deleted file mode 100644 index 8d462a6..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.monitor.ui.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.mylyn.monitor.activity.tracking.enabled.checked=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.tasks.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.tasks.ui.prefs deleted file mode 100644 index 2b60c21..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.tasks.ui.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -migrated.task.repositories.secure.store=true -org.eclipse.mylyn.tasks.ui.filters.nonmatching=true -org.eclipse.mylyn.tasks.ui.filters.nonmatching.encouraged=true -org.eclipse.mylyn.tasks.ui.welcome.message=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.oomph.workingsets.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.oomph.workingsets.prefs deleted file mode 100644 index a9ca0a1..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.oomph.workingsets.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -working.set.group=\n\n diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.recommenders.completion.rcp.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.recommenders.completion.rcp.prefs deleted file mode 100644 index b9bd711..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.recommenders.completion.rcp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -completion_tips_seen=org.eclipse.recommenders.completion.rcp.tips.discovery\:org.eclipse.recommenders.completion.rcp.tips.types -eclipse.preferences.version=1 diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.search.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.search.prefs deleted file mode 100644 index cec65c4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.search.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.search.defaultPerspective=org.eclipse.search.defaultPerspective.none diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.team.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.team.ui.prefs deleted file mode 100644 index 56cd496..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.team.ui.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.team.ui.first_time=false diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.browser.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.browser.prefs deleted file mode 100644 index 99489cd..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.browser.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -internalWebBrowserHistory=file\:/C\:/Users/Alvaro/Desktop/workspace/UnitParser/UnitParser.doc/index.html|*|file\:/C\:/Users/Alvaro/Desktop/workspace/UnitParser/doc/asdfas.doc/index.html|*| diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.editors.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.editors.prefs deleted file mode 100644 index 61f3bb8..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.editors.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -overviewRuler_migration=migrated_3.1 diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.ide.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.ide.prefs deleted file mode 100644 index 3720e89..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.ide.prefs +++ /dev/null @@ -1,5 +0,0 @@ -PROBLEMS_FILTERS_MIGRATE=true -eclipse.preferences.version=1 -platformState=1495829036829 -quickStart=false -tipsAndTricks=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.prefs deleted file mode 100644 index 08076f2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -showIntro=false diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.workbench.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.workbench.prefs deleted file mode 100644 index dd77496..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.ui.workbench.prefs +++ /dev/null @@ -1,3 +0,0 @@ -//org.eclipse.ui.commands/state/org.eclipse.ui.navigator.resources.nested.changeProjectPresentation/org.eclipse.ui.commands.radioState=false -PLUGINS_NOT_ACTIVATED_ON_STARTUP=org.eclipse.m2e.discovery; -eclipse.preferences.version=1 diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.sse.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.sse.ui.prefs deleted file mode 100644 index 9acd5df..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.sse.ui.prefs +++ /dev/null @@ -1,4 +0,0 @@ -content_assist_number_of_computers=3 -eclipse.preferences.version=1 -useAnnotationsPrefPage=true -useQuickDiffPrefPage=true diff --git a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.ui.prefs b/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.ui.prefs deleted file mode 100644 index 1af4ef7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.ui.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.xml.ui.internal.tabletree.XMLMultiPageEditorPart.lastActivePage=1 diff --git a/all_code/.metadata/.plugins/org.eclipse.debug.core/.launches/Testing.launch b/all_code/.metadata/.plugins/org.eclipse.debug.core/.launches/Testing.launch deleted file mode 100644 index 06414f2..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.debug.core/.launches/Testing.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.debug.ui/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.debug.ui/dialog_settings.xml deleted file mode 100644 index 2d1c107..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.debug.ui/dialog_settings.xml +++ /dev/null @@ -1,23 +0,0 @@ - -
-
- - - - - -
-
- - - -
-
- - - - - - -
-
diff --git a/all_code/.metadata/.plugins/org.eclipse.debug.ui/launchConfigurationHistory.xml b/all_code/.metadata/.plugins/org.eclipse.debug.ui/launchConfigurationHistory.xml deleted file mode 100644 index da5aef1..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.debug.ui/launchConfigurationHistory.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi b/all_code/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi deleted file mode 100644 index 2797662..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi +++ /dev/null @@ -1,2430 +0,0 @@ - - - - activeSchemeId:org.eclipse.ui.defaultAcceleratorConfiguration - ModelMigrationProcessor.001 - - - - - - - - topLevel - shellMaximized - - - - - persp.actionSet:org.eclipse.mylyn.doc.actionSet - persp.actionSet:org.eclipse.mylyn.tasks.ui.navigation - persp.actionSet:org.eclipse.ui.cheatsheets.actionSet - persp.actionSet:org.eclipse.search.searchActionSet - persp.actionSet:org.eclipse.ui.edit.text.actionSet.annotationNavigation - persp.actionSet:org.eclipse.ui.edit.text.actionSet.navigation - persp.actionSet:org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo - persp.actionSet:org.eclipse.ui.externaltools.ExternalToolsSet - persp.actionSet:org.eclipse.ui.actionSet.keyBindings - persp.actionSet:org.eclipse.ui.actionSet.openFiles - persp.actionSet:org.eclipse.debug.ui.launchActionSet - persp.actionSet:org.eclipse.jdt.ui.JavaActionSet - persp.actionSet:org.eclipse.jdt.ui.JavaElementCreationActionSet - persp.actionSet:org.eclipse.ui.NavigateActionSet - persp.viewSC:org.eclipse.jdt.ui.PackageExplorer - persp.viewSC:org.eclipse.jdt.ui.TypeHierarchy - persp.viewSC:org.eclipse.jdt.ui.SourceView - persp.viewSC:org.eclipse.jdt.ui.JavadocView - persp.viewSC:org.eclipse.search.ui.views.SearchView - persp.viewSC:org.eclipse.ui.console.ConsoleView - persp.viewSC:org.eclipse.ui.views.ContentOutline - persp.viewSC:org.eclipse.ui.views.ProblemView - persp.viewSC:org.eclipse.ui.views.ResourceNavigator - persp.viewSC:org.eclipse.ui.views.TaskList - persp.viewSC:org.eclipse.ui.views.ProgressView - persp.viewSC:org.eclipse.ui.navigator.ProjectExplorer - persp.viewSC:org.eclipse.ui.texteditor.TemplatesView - persp.viewSC:org.eclipse.pde.runtime.LogView - persp.newWizSC:org.eclipse.jdt.ui.wizards.JavaProjectWizard - persp.newWizSC:org.eclipse.jdt.ui.wizards.NewPackageCreationWizard - persp.newWizSC:org.eclipse.jdt.ui.wizards.NewClassCreationWizard - persp.newWizSC:org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard - persp.newWizSC:org.eclipse.jdt.ui.wizards.NewEnumCreationWizard - persp.newWizSC:org.eclipse.jdt.ui.wizards.NewAnnotationCreationWizard - persp.newWizSC:org.eclipse.jdt.ui.wizards.NewSourceFolderCreationWizard - persp.newWizSC:org.eclipse.jdt.ui.wizards.NewSnippetFileCreationWizard - persp.newWizSC:org.eclipse.jdt.ui.wizards.NewJavaWorkingSetWizard - persp.newWizSC:org.eclipse.ui.wizards.new.folder - persp.newWizSC:org.eclipse.ui.wizards.new.file - persp.newWizSC:org.eclipse.ui.editors.wizards.UntitledTextFileWizard - persp.perspSC:org.eclipse.jdt.ui.JavaBrowsingPerspective - persp.perspSC:org.eclipse.debug.ui.DebugPerspective - persp.viewSC:org.eclipse.ant.ui.views.AntView - persp.showIn:org.eclipse.egit.ui.RepositoriesView - persp.actionSet:org.eclipse.debug.ui.breakpointActionSet - persp.actionSet:org.eclipse.jdt.debug.ui.JDTDebugActionSet - persp.newWizSC:org.eclipse.jdt.junit.wizards.NewTestCaseCreationWizard - persp.actionSet:org.eclipse.jdt.junit.JUnitActionSet - persp.showIn:org.eclipse.jdt.ui.PackageExplorer - persp.showIn:org.eclipse.team.ui.GenericHistoryView - persp.showIn:org.eclipse.ui.views.ResourceNavigator - persp.showIn:org.eclipse.ui.navigator.ProjectExplorer - persp.viewSC:org.eclipse.mylyn.tasks.ui.views.tasks - persp.newWizSC:org.eclipse.mylyn.tasks.ui.wizards.new.repository.task - persp.actionSet:org.eclipse.debug.ui.debugActionSet - - - - org.eclipse.e4.primaryNavigationStack - - - - - - - - - - - - - - - org.eclipse.e4.secondaryDataStack - Debug - - - - - - - - - - - - - - - - org.eclipse.e4.secondaryNavigationStack - - - - - - - - - - - persp.actionSet:org.eclipse.mylyn.doc.actionSet - persp.actionSet:org.eclipse.mylyn.tasks.ui.navigation - persp.actionSet:org.eclipse.ui.cheatsheets.actionSet - persp.actionSet:org.eclipse.search.searchActionSet - persp.actionSet:org.eclipse.ui.edit.text.actionSet.annotationNavigation - persp.actionSet:org.eclipse.ui.edit.text.actionSet.navigation - persp.actionSet:org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo - persp.actionSet:org.eclipse.ui.externaltools.ExternalToolsSet - persp.actionSet:org.eclipse.ui.actionSet.keyBindings - persp.actionSet:org.eclipse.ui.actionSet.openFiles - persp.actionSet:org.eclipse.debug.ui.launchActionSet - persp.actionSet:org.eclipse.debug.ui.debugActionSet - persp.viewSC:org.eclipse.debug.ui.DebugView - persp.viewSC:org.eclipse.debug.ui.VariableView - persp.viewSC:org.eclipse.debug.ui.BreakpointView - persp.viewSC:org.eclipse.debug.ui.ExpressionView - persp.viewSC:org.eclipse.ui.views.ContentOutline - persp.viewSC:org.eclipse.ui.console.ConsoleView - persp.viewSC:org.eclipse.ui.views.TaskList - persp.viewSC:org.eclipse.ant.ui.views.AntView - persp.actionSet:org.eclipse.ui.NavigateActionSet - persp.actionSet:org.eclipse.debug.ui.breakpointActionSet - persp.viewSC:org.eclipse.pde.runtime.LogView - persp.showIn:org.eclipse.egit.ui.RepositoriesView - persp.actionSet:org.eclipse.jdt.debug.ui.JDTDebugActionSet - persp.viewSC:org.eclipse.jdt.debug.ui.DisplayView - persp.perspSC:org.eclipse.jdt.ui.JavaPerspective - persp.perspSC:org.eclipse.jdt.ui.JavaBrowsingPerspective - persp.actionSet:org.eclipse.jdt.ui.JavaActionSet - persp.showIn:org.eclipse.jdt.ui.PackageExplorer - persp.perspSC:org.eclipse.wst.xml.ui.perspective - - - - - org.eclipse.e4.primaryNavigationStack - - - - - - - - - - - - - - - - org.eclipse.e4.secondaryNavigationStack - - - - - - - org.eclipse.e4.secondaryDataStack - - - - - - - - - - - - - - - - - - - - View - categoryTag:Help - - - - - View - categoryTag:General - - ViewMenu - menuContribution:menu - - - - - - - View - categoryTag:Help - - - - org.eclipse.e4.primaryDataStack - EditorStack - active - - - Editor - org.eclipse.jdt.ui.CompilationUnitEditor - removeOnHide - - - - Editor - org.eclipse.jdt.ui.CompilationUnitEditor - removeOnHide - - - - Editor - org.eclipse.ui.DefaultTextEditor - removeOnHide - active - activeOnClose - - - - - - - - View - categoryTag:Java - - ViewMenu - menuContribution:menu - - - menuContribution:popup - popup:org.eclipse.jdt.ui.PackageExplorer - - - menuContribution:popup - popup:org.eclipse.jdt.ui.PackageExplorer - - - - - - - View - categoryTag:Java - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - - View - categoryTag:General - - ViewMenu - menuContribution:menu - - - menuContribution:popup - popup:org.eclipse.ui.views.ProblemView - popup:org.eclipse.ui.ide.MarkersView - - - menuContribution:popup - popup:org.eclipse.ui.views.ProblemView - popup:org.eclipse.ui.ide.MarkersView - - - - - - - View - categoryTag:Java - - - - - - View - categoryTag:Java - - ViewMenu - menuContribution:menu - - - - - - - - View - categoryTag:General - - ViewMenu - menuContribution:menu - - - - - - - - View - categoryTag:General - - ViewMenu - menuContribution:menu - - - menuContribution:popup - popup:org.eclipse.debug.ui.ProcessConsoleType.#ContextMenu - - - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - - View - categoryTag:General - - ViewMenu - menuContribution:menu - - - - - - - View - categoryTag:General - - - - - View - categoryTag:Ant - - - - - View - categoryTag:Git - - - - - View - categoryTag:Java - - - - - - View - categoryTag:Mylyn - - ViewMenu - menuContribution:menu - - - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - - View - categoryTag:Debug - - ViewMenu - menuContribution:menu - - - menuContribution:popup - popup:org.eclipse.debug.ui.DebugView - - - menuContribution:popup - popup:org.eclipse.debug.ui.DebugView - - - menuContribution:popup - popup:org.eclipse.debug.ui.DebugView - - - menuContribution:popup - popup:org.eclipse.debug.ui.DebugView - - - - - - - - View - categoryTag:Debug - - ViewMenu - menuContribution:menu - - - - - - - - View - categoryTag:Debug - - ViewMenu - menuContribution:menu - - - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Debug - - - - - View - categoryTag:General - - - - toolbarSeparator - - - - Draggable - - - - toolbarSeparator - - - - Draggable - - - Draggable - - - Draggable - - - Draggable - - - toolbarSeparator - - - - Draggable - - - - toolbarSeparator - - - - toolbarSeparator - - - - Draggable - - - stretch - SHOW_RESTORE_MENU - - - Draggable - HIDEABLE - SHOW_RESTORE_MENU - - - - - stretch - - - Draggable - - - Draggable - - - - - TrimStack - Draggable - - - TrimStack - Draggable - - - - - TrimStack - Draggable - - - TrimStack - Draggable - - - TrimStack - Draggable - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - platform:win32 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - platform:win32 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Editor - - - - - View - categoryTag:Ant - - - - - View - categoryTag:Gradle - - - - - View - categoryTag:Gradle - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Git - - - - - View - categoryTag:Git - - - - - View - categoryTag:Git - - - - - View - categoryTag:Git - - - - - View - categoryTag:Git - - - - - View - categoryTag:General - - - - - View - categoryTag:Help - - - - - View - categoryTag:Debug - - - - - View - categoryTag:Java - - - - - View - categoryTag:Java - - - - - View - categoryTag:Java - - - - - View - categoryTag:Java Browsing - - - - - View - categoryTag:Java Browsing - - - - - View - categoryTag:Java Browsing - - - - - View - categoryTag:Java Browsing - - - - - View - categoryTag:Java - - - - - View - categoryTag:General - - - - - View - categoryTag:Java - - - - - View - categoryTag:Java - - - - - View - categoryTag:Maven - - - - - View - categoryTag:Maven - - - - - View - categoryTag:Mylyn - - - - - View - categoryTag:Mylyn - - - - - View - categoryTag:Mylyn - - - - - View - categoryTag:Mylyn - - - - - View - categoryTag:Oomph - - - - - View - categoryTag:Code Recommenders - - - - - View - categoryTag:Code Recommenders - - - - - View - categoryTag:Code Recommenders - - - - - View - categoryTag:Code Recommenders - - - - - View - categoryTag:Code Recommenders - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:Team - - - - - View - categoryTag:Team - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:Help - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:General - - - - - View - categoryTag:XML - - - - - View - categoryTag:XML - - - - glue - move_after:PerspectiveSpacer - SHOW_RESTORE_MENU - - - move_after:Spacer Glue - HIDEABLE - SHOW_RESTORE_MENU - - - glue - move_after:SearchField - SHOW_RESTORE_MENU - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/http-cache/segments.gen b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/http-cache/segments.gen deleted file mode 100644 index 63a7ec9..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/http-cache/segments.gen and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/http-cache/segments_1 b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/http-cache/segments_1 deleted file mode 100644 index 259ef30..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/http-cache/segments_1 and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.fdt b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.fdt deleted file mode 100644 index d5abf41..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.fdt and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.fdx b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.fdx deleted file mode 100644 index b8ee809..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.fdx and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.fnm b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.fnm deleted file mode 100644 index 523c92e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.fnm +++ /dev/null @@ -1 +0,0 @@ -ýÿÿÿversion \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.frq b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.frq deleted file mode 100644 index e69de29..0000000 diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.nrm b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.nrm deleted file mode 100644 index cf8dc75..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.nrm +++ /dev/null @@ -1 +0,0 @@ -NRMÿ \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.tii b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.tii deleted file mode 100644 index ebd518d..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.tii and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.tis b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.tis deleted file mode 100644 index ebd518d..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/_0.tis and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/segments.gen b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/segments.gen deleted file mode 100644 index 63a7ec9..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/segments.gen and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/segments_1 b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/segments_1 deleted file mode 100644 index 2d0ce95..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/segments_1 and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/write.lock b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/local-history/write.lock deleted file mode 100644 index e69de29..0000000 diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.fdt b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.fdt deleted file mode 100644 index d5abf41..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.fdt and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.fdx b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.fdx deleted file mode 100644 index b8ee809..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.fdx and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.fnm b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.fnm deleted file mode 100644 index 523c92e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.fnm +++ /dev/null @@ -1 +0,0 @@ -ýÿÿÿversion \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.frq b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.frq deleted file mode 100644 index e69de29..0000000 diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.nrm b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.nrm deleted file mode 100644 index cf8dc75..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.nrm +++ /dev/null @@ -1 +0,0 @@ -NRMÿ \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.tii b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.tii deleted file mode 100644 index ebd518d..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.tii and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.tis b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.tis deleted file mode 100644 index ebd518d..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/_0.tis and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/segments.gen b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/segments.gen deleted file mode 100644 index 63a7ec9..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/segments.gen and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/segments_1 b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/segments_1 deleted file mode 100644 index 1493174..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/remote-history/segments_1 and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/server-config.json b/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/server-config.json deleted file mode 100644 index 4fe4b18..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.epp.logging.aeri.ide/org.eclipse.epp.logging.aeri.ide.server/server-config.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "version": "v1", - "title": "Eclipse", - "timestamp": 1497262232638, - "ttl": 10080, - "helpUrl": "https://dev.eclipse.org/recommenders/community/aeri/v2/help/", - "feedbackUrl": "http://ctrlflow.com/automated-error-reporting", - "aboutUrl": "https://wiki.eclipse.org/EPP/Logging", - "submitUrl": "https://dev.eclipse.org/recommenders/community/confess/0.6/reports/", - "maxReportSize": 262144, - "problemsUrl": "https://www.eclipse.org/downloads/download.php?r\u003d1\u0026file\u003d/technology/epp/logging/problems.zip", - "problemsTtl": 20160, - "interestUrl": "https://dev.eclipse.org/recommenders/community/confess/v2/interest", - "connectTimeout": 10, - "socketTimeout": 10, - "acceptedProducts": [ - "org.eclipse.*", - "org.fordiac.*" - ], - "acceptedPlugins": [ - "org.apache.log4j.*", - "org.eclipse.*", - "org.fordiac.*" - ], - "acceptedPackages": [ - "ch.qos.*", - "com.cforcoding.*", - "com.google.*", - "com.gradleware.tooling.*", - "com.mountainminds.eclemma.*", - "com.naef.*", - "com.sun.*", - "java.*", - "javafx.*", - "javax.*", - "org.apache.*", - "org.eclipse.*", - "org.fordiac.*", - "org.gradle.*", - "org.jacoco.*", - "org.osgi.*", - "org.slf4j.*", - "sun.*" - ], - "requiredPackages": [ - "com.cforcoding.*", - "com.gradleware.tooling.*", - "com.mountainminds.eclemma.*", - "com.naef.*", - "org.eclipse.*", - "org.fordiac.*", - "org.gradle.*", - "org.jacoco.*" - ], - "acceptOtherPackages": false, - "acceptUiFreezes": true, - "ignoredStatuses": [ - ":java.io.IOException:There is not enough space on the disk", - ":java.net.*:", - "org.eclipse.core.filesystem::Could not delete*", - "org.eclipse.core.filesystem::Could not move*", - "org.eclipse.core.resources:org.eclipse.core.internal.resources.ResourceException:Resource is out of sync with the file system*", - "org.eclipse.core.runtime::Invalid input url*", - "org.eclipse.epp.mpc.ui:java.io.IOException:", - "org.eclipse.equinox.p2.*::", - "org.eclipse.jface:java.io.IOException:Unable to resolve plug-in*", - "org.eclipse.oomph.setup.core:$org.apache.http.ConnectionClosedException:", - "org.eclipse.pde.core::The current target platform contains errors*", - "org.eclipse.ui::Conflicting handlers for*" - ], - "problemsZipLastDownloadTimestamp": 0 -} \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1005863892.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/1005863892.index deleted file mode 100644 index b876dff..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1005863892.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1477788888.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/1477788888.index deleted file mode 100644 index d4d67f4..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1477788888.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/148409970.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/148409970.index deleted file mode 100644 index bb23391..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/148409970.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1484906476.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/1484906476.index deleted file mode 100644 index 65608da..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1484906476.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1657330681.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/1657330681.index deleted file mode 100644 index 26805ba..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1657330681.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1689259093.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/1689259093.index deleted file mode 100644 index 98c0932..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/1689259093.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/194259052.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/194259052.index deleted file mode 100644 index fd1e25e..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/194259052.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/2272273464.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/2272273464.index deleted file mode 100644 index 54fe66c..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/2272273464.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/2470519452.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/2470519452.index deleted file mode 100644 index 59f4830..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/2470519452.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/2631975291.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/2631975291.index deleted file mode 100644 index f4b760a..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/2631975291.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/2709225165.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/2709225165.index deleted file mode 100644 index cbaa2cb..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/2709225165.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/3141958188.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/3141958188.index deleted file mode 100644 index 8b73a0c..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/3141958188.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/3620471903.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/3620471903.index deleted file mode 100644 index 3191fe3..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/3620471903.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/3666609613.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/3666609613.index deleted file mode 100644 index 9add4c7..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/3666609613.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/3698447926.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/3698447926.index deleted file mode 100644 index 7e0dd4e..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/3698447926.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/4265864773.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/4265864773.index deleted file mode 100644 index 23573ff..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/4265864773.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/559129880.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/559129880.index deleted file mode 100644 index ff6f4bf..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/559129880.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/628019425.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/628019425.index deleted file mode 100644 index ce9a98d..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/628019425.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/648612256.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/648612256.index deleted file mode 100644 index a4b3912..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/648612256.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/848469205.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/848469205.index deleted file mode 100644 index c2e6602..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/848469205.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/922380862.index b/all_code/.metadata/.plugins/org.eclipse.jdt.core/922380862.index deleted file mode 100644 index 911d26b..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/922380862.index and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/assumedExternalFilesCache b/all_code/.metadata/.plugins/org.eclipse.jdt.core/assumedExternalFilesCache deleted file mode 100644 index a4d5c20..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/assumedExternalFilesCache and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/externalFilesCache b/all_code/.metadata/.plugins/org.eclipse.jdt.core/externalFilesCache deleted file mode 100644 index 070c413..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/externalFilesCache and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/externalLibsTimeStamps b/all_code/.metadata/.plugins/org.eclipse.jdt.core/externalLibsTimeStamps deleted file mode 100644 index 7e82fa0..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/externalLibsTimeStamps and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/indexNamesMap.txt b/all_code/.metadata/.plugins/org.eclipse.jdt.core/indexNamesMap.txt deleted file mode 100644 index 0295c3b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.jdt.core/indexNamesMap.txt +++ /dev/null @@ -1 +0,0 @@ -INDEX VERSION 1.130 diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/javaLikeNames.txt b/all_code/.metadata/.plugins/org.eclipse.jdt.core/javaLikeNames.txt deleted file mode 100644 index 8586397..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.jdt.core/javaLikeNames.txt +++ /dev/null @@ -1 +0,0 @@ -java \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/nonChainingJarsCache b/all_code/.metadata/.plugins/org.eclipse.jdt.core/nonChainingJarsCache deleted file mode 100644 index e89c6b9..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/nonChainingJarsCache and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/savedIndexNames.txt b/all_code/.metadata/.plugins/org.eclipse.jdt.core/savedIndexNames.txt deleted file mode 100644 index 8d2c21e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.jdt.core/savedIndexNames.txt +++ /dev/null @@ -1,22 +0,0 @@ -INDEX VERSION 1.130+C:\Users\Alvaro\Desktop\workspace\.metadata\.plugins\org.eclipse.jdt.core -3141958188.index -3620471903.index -628019425.index -3666609613.index -1005863892.index -2709225165.index -1484906476.index -4265864773.index -194259052.index -848469205.index -922380862.index -1689259093.index -648612256.index -559129880.index -2631975291.index -148409970.index -2470519452.index -2272273464.index -1477788888.index -1657330681.index -3698447926.index diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.core/variablesAndContainers.dat b/all_code/.metadata/.plugins/org.eclipse.jdt.core/variablesAndContainers.dat deleted file mode 100644 index 01dd238..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.jdt.core/variablesAndContainers.dat and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.debug.ui/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.jdt.debug.ui/dialog_settings.xml deleted file mode 100644 index a8fba90..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.jdt.debug.ui/dialog_settings.xml +++ /dev/null @@ -1,11 +0,0 @@ - -
-
-
-
- - - - -
-
diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.launching/.install.xml b/all_code/.metadata/.plugins/org.eclipse.jdt.launching/.install.xml deleted file mode 100644 index 0b8c0e7..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.jdt.launching/.install.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.launching/libraryInfos.xml b/all_code/.metadata/.plugins/org.eclipse.jdt.launching/libraryInfos.xml deleted file mode 100644 index 7a931b1..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.jdt.launching/libraryInfos.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.ui/OpenTypeHistory.xml b/all_code/.metadata/.plugins/org.eclipse.jdt.ui/OpenTypeHistory.xml deleted file mode 100644 index a4ee3cb..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.jdt.ui/OpenTypeHistory.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.ui/QualifiedTypeNameHistory.xml b/all_code/.metadata/.plugins/org.eclipse.jdt.ui/QualifiedTypeNameHistory.xml deleted file mode 100644 index 3b6a9bd..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.jdt.ui/QualifiedTypeNameHistory.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml deleted file mode 100644 index 851fe99..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml +++ /dev/null @@ -1,140 +0,0 @@ - -
- - - - - - - - - - - - -
- - - - - - - - -
-
- - - - - -
-
- - -
-
- -
-
- - - - - - - - - - - - -
-
- - - - - - - - - - - - - - - - - - -
-
- - - -
-
- - - -
-
-
-
- - - -
-
-
-
- - - -
-
- -
-
- -
-
- - - - - -
-
- - -
-
- - - - - - - - - - - - - - - - - - - - - - -
-
-
-
diff --git a/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/.workspace/2017/6/22/refactorings.history b/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/.workspace/2017/6/22/refactorings.history deleted file mode 100644 index 9c9fa0f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/.workspace/2017/6/22/refactorings.history +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/.workspace/2017/6/22/refactorings.index b/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/.workspace/2017/6/22/refactorings.index deleted file mode 100644 index 2c301dc..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/.workspace/2017/6/22/refactorings.index +++ /dev/null @@ -1,2 +0,0 @@ -1496328979605 Delete resource 'testing' -1496495215737 Delete resource 'test0' diff --git a/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/test0/2017/6/22/refactorings.history b/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/test0/2017/6/22/refactorings.history deleted file mode 100644 index 098c4f9..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/test0/2017/6/22/refactorings.history +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/test0/2017/6/22/refactorings.index b/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/test0/2017/6/22/refactorings.index deleted file mode 100644 index 2220107..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ltk.core.refactoring/.refactorings/test0/2017/6/22/refactorings.index +++ /dev/null @@ -1 +0,0 @@ -1496495198777 Move package diff --git a/all_code/.metadata/.plugins/org.eclipse.ltk.ui.refactoring/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.ltk.ui.refactoring/dialog_settings.xml deleted file mode 100644 index a0d67e4..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ltk.ui.refactoring/dialog_settings.xml +++ /dev/null @@ -1,19 +0,0 @@ - -
-
- - -
-
- - -
-
- - - -
-
- -
-
diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/_0.cfs b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/_0.cfs deleted file mode 100644 index 10c0c85..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/_0.cfs and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/segments.gen b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/segments.gen deleted file mode 100644 index 225a55b..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/segments.gen and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/segments_2 b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/segments_2 deleted file mode 100644 index 429858f..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/segments_2 and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/write.lock b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/05b0fe8524860bd73cbb07ef30fb34cc/write.lock deleted file mode 100644 index e69de29..0000000 diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/_0.cfs b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/_0.cfs deleted file mode 100644 index 778f3e8..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/_0.cfs and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/segments.gen b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/segments.gen deleted file mode 100644 index 225a55b..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/segments.gen and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/segments_2 b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/segments_2 deleted file mode 100644 index ef084b8..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/segments_2 and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/write.lock b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/8146dbc5f790367a305e08497637c712/write.lock deleted file mode 100644 index e69de29..0000000 diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/_0.cfs b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/_0.cfs deleted file mode 100644 index 2510e88..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/_0.cfs and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/segments.gen b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/segments.gen deleted file mode 100644 index 225a55b..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/segments.gen and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/segments_2 b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/segments_2 deleted file mode 100644 index da08b2d..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/segments_2 and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/write.lock b/all_code/.metadata/.plugins/org.eclipse.m2e.core/nexus/830bc118332e77292949ed1e6d2fabe0/write.lock deleted file mode 100644 index e69de29..0000000 diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.core/workspaceState.ser b/all_code/.metadata/.plugins/org.eclipse.m2e.core/workspaceState.ser deleted file mode 100644 index 4632fc4..0000000 Binary files a/all_code/.metadata/.plugins/org.eclipse.m2e.core/workspaceState.ser and /dev/null differ diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.logback.configuration/0.log b/all_code/.metadata/.plugins/org.eclipse.m2e.logback.configuration/0.log deleted file mode 100644 index f0e737b..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.m2e.logback.configuration/0.log +++ /dev/null @@ -1,66 +0,0 @@ -2017-05-29 13:41:58,196 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-29 13:42:16,378 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-29 15:58:12,292 [Worker-3] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-29 17:19:36,542 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-29 21:35:44,726 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-30 10:02:58,065 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-30 10:24:07,958 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-30 13:09:44,704 [Worker-3] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is out-of-date. Trying to update. -2017-05-30 15:18:58,177 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-30 18:14:50,708 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-30 21:15:55,087 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-31 10:07:43,608 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-31 15:34:14,354 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is out-of-date. Trying to update. -2017-05-31 17:45:17,403 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-05-31 22:55:37,494 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-01 15:45:37,756 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is out-of-date. Trying to update. -2017-06-01 16:42:35,439 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-01 16:55:54,349 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-01 20:37:54,809 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-02 12:26:19,121 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-02 16:06:20,030 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is out-of-date. Trying to update. -2017-06-02 18:05:43,901 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-02 20:08:08,564 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-02 21:08:41,924 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-02 21:31:23,462 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-02 21:55:33,669 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 11:12:13,959 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 11:15:57,749 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 12:35:33,529 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 14:50:50,743 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 15:51:31,786 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 16:51:38,072 [Worker-3] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is out-of-date. Trying to update. -2017-06-03 18:01:32,740 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 19:17:52,159 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 20:36:29,012 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 20:47:16,981 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 21:09:12,221 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-03 22:16:19,826 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-04 09:53:30,586 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-04 12:02:09,501 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-04 12:05:47,274 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-04 13:01:39,965 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-04 15:32:11,674 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-04 16:50:56,470 [Worker-3] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-05 21:53:11,379 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-05 21:54:51,128 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-06 09:57:32,964 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-06 13:00:58,240 [Worker-3] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is out-of-date. Trying to update. -2017-06-06 15:00:55,042 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-06 15:53:24,505 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-07 20:24:23,127 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is out-of-date. Trying to update. -2017-06-08 10:53:52,750 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-08 11:54:10,888 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-08 13:43:41,165 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-08 15:42:43,750 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-08 16:30:12,122 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-08 16:47:39,184 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-08 18:29:38,473 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-08 18:55:00,867 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-08 20:25:17,177 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is out-of-date. Trying to update. -2017-06-09 09:30:16,082 [Worker-2] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-09 10:46:10,453 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-09 11:40:55,584 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-09 11:43:24,728 [Worker-0] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-09 11:49:28,488 [Worker-1] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. -2017-06-12 12:10:31,557 [Worker-3] INFO c.g.t.t.d.PublishedGradleVersions - Gradle version information cache is up-to-date. Trying to read. diff --git a/all_code/.metadata/.plugins/org.eclipse.m2e.logback.configuration/logback.1.7.0.20160603-1933.xml b/all_code/.metadata/.plugins/org.eclipse.m2e.logback.configuration/logback.1.7.0.20160603-1933.xml deleted file mode 100644 index e33758c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.m2e.logback.configuration/logback.1.7.0.20160603-1933.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - %date [%thread] %-5level %logger{35} - %msg%n - - - OFF - - - - - ${org.eclipse.m2e.log.dir}/0.log - - ${org.eclipse.m2e.log.dir}/%i.log - 1 - 10 - - - 100MB - - - %date [%thread] %-5level %logger{35} - %msg%n - - - - - - WARN - - - - - - - - - - - - - - - diff --git a/all_code/.metadata/.plugins/org.eclipse.oomph.setup/workspace.setup b/all_code/.metadata/.plugins/org.eclipse.oomph.setup/workspace.setup deleted file mode 100644 index 1f73e14..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.oomph.setup/workspace.setup +++ /dev/null @@ -1,6 +0,0 @@ - - diff --git a/all_code/.metadata/.plugins/org.eclipse.search/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.search/dialog_settings.xml deleted file mode 100644 index 393805e..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.search/dialog_settings.xml +++ /dev/null @@ -1,203 +0,0 @@ - -
-
- -
-
- -
-
- -
-
- - - - - - -
- - - - - - - - - - -
-
- - - - - - - - - - -
-
- - - - - - - - - - -
-
- - - - - - - - - - -
-
- - - - - - - - - - -
-
- -
-
- - - - - - - - - - -
-
- - - - - - - - - - -
-
- - - - - - - - - - -
-
- - - - - - - - - - -
-
- - - - - - - - - - -
-
- - - - - - - - - - -
-
- - - - - - - - - - -
-
-
- -
-
- - - - - - - - - - - - -
-
- - - -
-
- -
-
- - -
-
- - - - - -
-
diff --git a/all_code/.metadata/.plugins/org.eclipse.ui.editors/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.ui.editors/dialog_settings.xml deleted file mode 100644 index 50f1edb..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ui.editors/dialog_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - -
-
-
-
diff --git a/all_code/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml deleted file mode 100644 index 445cc30..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml +++ /dev/null @@ -1,25 +0,0 @@ - -
- - - - -
- - - - - - - -
-
-
-
- - - - - -
-
diff --git a/all_code/.metadata/.plugins/org.eclipse.ui.intro/introstate b/all_code/.metadata/.plugins/org.eclipse.ui.intro/introstate deleted file mode 100644 index 02f134f..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ui.intro/introstate +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.ui.workbench.texteditor/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.ui.workbench.texteditor/dialog_settings.xml deleted file mode 100644 index 9c5fd9c..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ui.workbench.texteditor/dialog_settings.xml +++ /dev/null @@ -1,38 +0,0 @@ - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - - - -
-
diff --git a/all_code/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml deleted file mode 100644 index f65c372..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml +++ /dev/null @@ -1,26 +0,0 @@ - -
-
- - -
-
- - - - - - - - - - -
-
- - - - - -
-
diff --git a/all_code/.metadata/.plugins/org.eclipse.ui.workbench/workingsets.xml b/all_code/.metadata/.plugins/org.eclipse.ui.workbench/workingsets.xml deleted file mode 100644 index 2294530..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.ui.workbench/workingsets.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/all_code/.metadata/.plugins/org.eclipse.wst.sse.core/task-tags.properties b/all_code/.metadata/.plugins/org.eclipse.wst.sse.core/task-tags.properties deleted file mode 100644 index a78295d..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.wst.sse.core/task-tags.properties +++ /dev/null @@ -1,3 +0,0 @@ -# -#Wed May 31 22:57:50 CEST 2017 -task-tag-projects-already-scanned=Test,testing,UnitParser diff --git a/all_code/.metadata/.plugins/org.eclipse.wst.sse.ui/dialog_settings.xml b/all_code/.metadata/.plugins/org.eclipse.wst.sse.ui/dialog_settings.xml deleted file mode 100644 index 63fae25..0000000 --- a/all_code/.metadata/.plugins/org.eclipse.wst.sse.ui/dialog_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - -
-
-
-
diff --git a/all_code/.metadata/version.ini b/all_code/.metadata/version.ini deleted file mode 100644 index 03dc4e0..0000000 --- a/all_code/.metadata/version.ini +++ /dev/null @@ -1,3 +0,0 @@ -#Mon Jun 12 12:10:26 CEST 2017 -org.eclipse.core.runtime=2 -org.eclipse.platform=4.6.3.v20170301-0400 diff --git a/all_code/.recommenders/caches/identified-project-coordinates.json b/all_code/.recommenders/caches/identified-project-coordinates.json deleted file mode 100644 index ba2bbfc..0000000 --- a/all_code/.recommenders/caches/identified-project-coordinates.json +++ /dev/null @@ -1 +0,0 @@ -[[{"location":"C:\\Users\\Alvaro\\Desktop\\UnitParser.jar","type":"JAR","hints":{}},"ABSENT"],[{"location":"C:\\Users\\Alvaro\\Desktop\\workspace\\Test\\UnitParser.jar","type":"JAR","hints":{}},"ABSENT"]] \ No newline at end of file diff --git a/all_code/.recommenders/caches/manual-mappings.json b/all_code/.recommenders/caches/manual-mappings.json deleted file mode 100644 index 9e26dfe..0000000 --- a/all_code/.recommenders/caches/manual-mappings.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.fdt b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.fdt deleted file mode 100644 index ba10aeb..0000000 Binary files a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.fdt and /dev/null differ diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.fdx b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.fdx deleted file mode 100644 index 1ba41ae..0000000 Binary files a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.fdx and /dev/null differ diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.fnm b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.fnm deleted file mode 100644 index 98f1ed7..0000000 --- a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.fnm +++ /dev/null @@ -1,3 +0,0 @@ -ýÿÿÿ -coordinate fingerprintssymbolic-names -classifierselfcovrpovrmcallovrdselfmctor \ No newline at end of file diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.frq b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.frq deleted file mode 100644 index 6e7f714..0000000 --- a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.frq +++ /dev/null @@ -1,1109 +0,0 @@ -Õdͬ•ãïn1õ5}¿6ÙQyÑ_'¡EÕj3¥AÁ85Ÿ39Ù%+ÁAm»4‹?é?9·[Õ‰å¯8)éE½ã,í3Ó Å½ë!i•9‘b5©7ùW³D3à -ÛSÃ>ÉÍ-±…×õ/‡®½Oá­M1×8Q;ó%™:‹‹8Ýõ"û¥r“¡"Á£7û Á0ë9· -ù8×*é,»A±*‹ -3± åÿ;¯Rí —$—*… ™±#­Ÿ£ ÏPß9›5ß -ó0Óá‘GÍ<Ñ£:Ã4û!Ý ÇQÁ"‡±K­.ÝÅ:‹0Ñ ·4±Ó*Û&©A ÿBõ5Í Ç(«"‰0ýƒ§ ÝJ›"‰4›#™"•Û5¹1ÛŸßa±!Ïã­ÃPå,Û'ѳ:ý …%ñ8»4¯,¿A· Ç9ÝݯDá.‰ßB³Ï£ïBé0Ñ6‹µ ÍA¥/Û0ù!ûŸ*‡ï[‘#Ñ+ë6§<¿ ŸM¿"ù.›%ËD½%ƒã‰B‘ óO¯çB­­!ùÓ0—Dí £©')t)T-É2+»ƒ9Õ`-‡_»9ñ‘7Ý7…(ù×#é<·“$Å -»~…ýyÿ »"‹‘£YÉgË$Ár‰™f²•³«Z÷ƒJÏ+¹²ß ÍqÕ;ÍŸ<Ÿ–ÕQï‡ß2Ëc½ -í‰ÿ4³Ÿ‘Jõ¦ÙpóeÙ4Ý-å@ƒ©Ïfõ,¯AÏ[ÝN©Ç{ÇÉ;¡zë:ï`¹pù(©z•L±»±«ã§Ý±BÍ~§Jµ\ñM‘\ã×|ƒñ¿ÝEç.• × Ó_Õ?ƒ%›‘TÙ½€ó„™Øýjñ=‘ŠïqçI猓™|‹DA·2‡LÃc·§#ÑJµ-ë!¥6A§©ÙÉe±!·NÃíBG©A‰ GÅïó ¿ÙHç)µCñÍùç(oï·¹»MÙ!³Û©0·Feñé)»;×8uõ+aÅ -§6¹*§÷+‘“ñ8û÷aÝU¡Ógí©aÍ0ÿ$ý"¿!]ïDq‹r•å8ßZ9÷6á í)i‹ç ûF…Y×—5§[Éÿ.§—#«ÿµ?Ñ Ÿ)Ù]‹8‹&Õ™ë5Ñ;§…ë$»GÃé-O!¡%Ï*«%ÿ_ŸK•"«£@¯"—"}×ë0›aË!Á$‹Oç ¹g,Ó@]Í -Í6¯ÿ%‹nÅ -cÝ‹Pç!Cï廃ùLå#Õ&û"£«7• »™ ½ó#ù2¥µ*ï!ó")ëÓN¹ký­( -µ ýO™+‘FmÑ6£‹,W¿A“#Á“cÃ!ë`¡ -BYë Ë ç¿$½AKó*%——7;íAÅÁ+Ó5Ý7sk·D­Q剋rwó “¡oë!•ƒ4õ­1Å@Gù -•Uù%‡m§7£-©:—ÇMß6× ·³ åå2ÅP¡'• -á6IóFõ ÿ{¥]ÿ ñ8e“>­/× ±$‰M7¡ßA™Y•7 -¿*ç@Yé ƒ=Á)aà -±6Í*éO©&ŸV¯•W¿í¥ óÏ -•!—§ÿ?­,ÑÛ “áï#©eÉm½y!õ%‘;…2£¯!¡"Ÿ¥ƒõQÉ Ë*‰µ·ûJÿïl«Ë ¯4Õ7Y½Íc‘@™6Ï)³.± ‡3ý»' {ÝNë û_ŸA³9›(»"Yµ>Ù‡qi¥ó ½‡#ç¯A‰,­Xk· ™7ù*§*ÿU ß%Ó#éOÕ ßŸëí&›J³ó:³§!:±#uÛ7Ç9·e·Å.Ç6«"Ç¡Á ó`…%ß~›?5›QÇë—± -gU/ý£¦­OY­)=]UýyÑ=óã#'õd±2+§c‘;“?MÇ6‹#7ÃÇ6Õpá!Aõ%­A7ŸW!§+WU± §^‹"‹:U/‹ñ0¹?µ;‰=;µ NµsYÁÃ+eÑ ¡7×*¥ ËÿmƒVWÍÝ8ÃEe™Õ!×›GÏ ¡®Á“‘9Í:ë8×X忘¯ûÝP»‹‹rõUµ ÕIùŸ£#ùk›‰:‘¹Ý8ñ;ñ»gÍ -­m©›¿/› ¿„ƒ¹mÏR—l|³™ý‰÷"¯‰TŸŒ¿tÿbÛ^ËvÕ ‰vå%¡‡›!¥)…Eç"›Ùxç3Á Ç„Ó¦óGítÑ‚Ÿa¡£")ñ Ãç#õç7ÓP‹.ûy•ß|óyû÷+‘C£5ûlá¿Y·%³e¹—=7£ É ùcÕ•AãOÙ ÅC¹2Ï(ñ¥ É"Ó#ù2» ³6½˜Å¥ª¡Žï!‹Û›Ù••aÝ £‡>PÃ?™ å4×g‡ -Ãï$‡ ‡#ù -û3<§‚£3:ó8U›h¡ ‡<·On é”û;—…Ï ¡=ñ!£ »€Ë>“ VÍ[µLÿ3,»6÷RåÕìã σ Çi‹ã0“AÇ+áã(qéË…ï’Ë&½]Ýaý%Á#DZlj#¯cë“7˳>¹•õ5›ÕN¯ÇU‰i÷ß}ÑžçlÉ:Ã?› -éã¹4ÿUÉžmÇE-Ï »)Û.ñß‘8 -;‘(»I­8ë£U6‘Ù#ñN»Y“½ 3­89ùÿëÇ0ÓIß×7…\ãŽà É9×(Ù0© ¿±TÇËÛ -ÝQ1 -µ‰‰ ©íǦÇo3™ õó4͇©¿ß©?í%ïX½­#ã‹Ó“õu£fÍÓ/Á«"Ýé„1©2φ· -í$å|`/©¯»#U‰%ÝPŸ £‡ˆ·!±é‚«*C‡)‘«+ý )ó í^¿!—Oï’Í?Ù$Ë¡’‡ —7™{‹8ÓÙ «^‹ÃNíZ« Ño· £8×KË— Õ$áy7iÑ9ë ï"© -å.•cŸ7õnÙýT¯ów“¿K³0Ó ûnÁ íl'Ï -ËX)©!›oµ"é*ë{‹Xå!Oé¥ób9'åZÿïÅ!Ù1÷ý ·O³aƒ:ïµÿó#ÛÇ7ífï"ù.Ÿ"ÁC× ÉrŸ6‰Ç ÏF» ç…ÅG¥7™i¡ ÓŸš§ »;¿ ™3õ «}Ï! ù8‡xÛ7§A¹ Ó\¥ ûxÙ8ñ!—z¿‘¯9µZ—&ã“9™s‘"—˜ù ƒ+Ùzç·E×.³7£¥B³[Í7“|í!É¿9ÿ ¹µ ÿE¿5ï5!×=ýݯ8ƒßyÉ¥‘Í›#íO¡!µ™&½í7¹GM•6·V…!£Pù͵}û Ã$­bë1ãXù“÷?×çÅ.‰û‹ŒÃQƒÃé#ÿ‡¿;Å í— ½&à‹0÷3©3²ý#¡ §6Ï­Ù"õã»6Ù]ãÓgÑ"áýX‡S÷;»óPã$£?‡ ·0á7Ç>­(á/Õ9óZÏ+óÕ!íëÑ#ÿ«"É›[É&ù ³<› ëƒÙa»R«íKÅ0Ïçcç‰!g‚±™$_Á"Ç<é åÝ ÷b±HƒÝxûÓO• -ù\•"ÃýŽÇ !»6ù!ùùgõ û§¢Ã*“Éå"ñ˜ÍCß¹‡§‡B…#‡Ó#ó,¯`Ï&‹Ñã«Í+±#¡ É"½Z™Ëgç£ Ÿ\ßï“)íPùR݃!ûVß!ÉY¹(Á:‰)¿&‘ÿ™!ùµ £‰*ùJ—.Õ ·(£ÿ›/÷J±ýi• « ¥YÇí!é6§ûá$Ó(ë%«*ÛKå÷:µ—$¹<ý%ÿ‹¿E­6ËÕ“‘ßGå"™Ãé“«0á ¹Å‘× ×+± Ã*ËHÁág‰#ÝÏ–á·1Ç0©¤½ ¯×­ ÅùK« ÿà ãÙ!ía­©¯{§¥ÍÉg¥%Á±7Í0­ËïN£ßó%ÕTç ¥#Ù -m£U‘mà -«*Ýn½ E…4ß%—Ù:Ñe“ ƒ:»å »$¯N±¡,‡B'ýŸ"»‹9ý"É€Íå» ó••¥ïí)¿Bû¡;¥ !³£'§7Û‰J7<ƒéz¹ëùý{é ËkùÉ@á»s£Z£¿9—œÉ±:©MÍF×M…¹½#•ïY͇Ká.C¿"£ë:“,Ã##·ñ5Á•çû7‰'±!û%Û‘M¿¯'Ã<ÿGÑ<‘3‡4§”ÝVÃ3³—;Ñ™§B­hû2›Ÿz¿’±+·dµ®ûIõ(ñ#ű5É%¯Ím‰Nµ å.÷'÷ -óY¥9…V™ -áNÉ&¯3åvéxÙNùH½f“¿!× ‹?ÕMÑ%“9·BÉÁ@ÁÅu Í‘¡.·ã"©`¥=ó ãßE£.© µ6§ ÏG¹3Ç -Ÿ‘E§ ÏÁ2ép!»¹9ÿAó…pÕžÛí Ù›háë>Ó<Ùï1ç7¡Q¡óñEƒ¿«é‘aÉ0å8ƒ­Põ-ÿ¥á?à -›ï[ÿ󚧟Táz™Ãù}óç’õÇ%8Û&ë×Ý ¥Ï)·9Û:ótËýÕh»·k£ßÛƒ…=Ï3Ñ™‰•Á««ùŸ"» ­7ï*Á é*ó5—“ƒ™ËOåÅ0õ!ß$‰ÙùõÛÑAÝ%§ÍGï#¯ÿ ç ¿9¡(é á(ï Ã9©‰Á ‡ Õ>é#­.ÝŸ7ϯ Ý8Áß#‰3½#£ã­ã½NÉÁ i»xŸ'•å"ƒÙé«9å×`ç C­5¯‹"¯‡’ññ…8ß ß2õ¿ -á5— -¿1÷© í6ã% § ±M‹‡í"¿ õ/Ÿ û™Oßåë$™Ç6ï)¹ƒ8Ã8»Å1©¯"ý·ƒ4ï'¹ã •…›#ã±&™ Ë)ÝŸ;±…2õý ßÙ#Å!Ï#(¥µ#•(×"­"‘ƒ#Ñé;‰1×õ— ƒ&Õ½!û;Ùé Ý3×"Ëí ÷"ÿ»Hñ ï³7»ë$Ù éÃ#©Ë!£ Í9­2™ ñ ‰(›#ÇD›Ó#Ó“"™«8« »5Ë -×,¡#½½ýÏ$¿Û ý"¥ «#•Ï"Ù-» -ƒ‰‡6£+Õÿ ƒ¿0û ÙÅã -¹6÷÷±"ƒ(±4'— -ã:Û%»ãÅ9ã¹6Ó › ñ:«2«™ ïÝ Ë7Ñ ƒ1Ÿ· ÕMß ý …5Ó#ù"Ç ‘ó.«9Ýí9ûÍ%Ë0ïÓ!Ÿ‘,ï £6å—Û_µ?»K‹™]û1çw·‰7AoÉLëa‡8É—¢YÕ«bÃJ­˜É³ƒTí¡ƒnÁ³—ý -»[·!hk•rï!¯ÁX5ƒgÍIãó}çëŒÿXIñç‘ÿtÃ(¿…‹™!Ý4™*{eï8• É\çÑ.‹Q¡‘ ëå0¥Të£-ó0Ññà ×ûaé&½é3×ß‹¡a÷…-Ë(åV‡…=Ù ãç ÿ4›¡ÿ9ß0Å(§6ƒ(Ý3ý‘)¯a›ÏÿO •í0‘§/­<ñ!Û½ §¡g“U ³17õ*“&Ý•+åxÑ/ç>ã"Ñ÷ˆÉá׃Xû™¹,í£%ë!³-µ!ƒ'õ‹>•)٠ç•1÷P…ù½bÃ(ç Ç8ÝÝ1Çó ÿ\ß5«,¥"¹0×Ëx½ -ñ7Ï··QÍ-Ï ‡4Ý «1å™VÓ.Ÿ¿µ+à ó·!ûm‡« Ý2¹6£‹›E×0ëCÅ ­0‡£)‰Ù¯$á¿ïY¹‹4…Å=×»6•’‘2»6… ›2ÛK™í"×#ÝP­™,“ ßÁ_™á\Å…4éDý/·66Ë -Ù-…½ ©å\¯(õñ3¡Véõ8• Å3õƒ/‰9µ=‡É½`­í»~Ù ¡å“ Éb¹­_Ý1ÁÅ)§Lï}å“£,×÷ íW•&Ó·Pß.ñOå'Ã(ƒíûQ±1 é óEÉ:ë(ë“#áëJÏ¥4õ×\ÿ"Õ4™³á Ý"ù'ÝGõ¹"Ÿ(¹Õaÿ›T¡1¡ÿù/Ï»&³*Ý)á ‡ ÷(¥ -Ÿ £ ½¥+…V×,ÝQ½¿Wé3ß÷Låé™(Ç áEÑ3σr÷…Õ+›%åãUÑ Í×Å “P­‡ª×]űpé9¹…zÓLѯ»‘ÓA— ‡žÿ]©·må!í»!ÿó ÷c•1÷%é ó#É9Ÿ åx§û }å<ƒ\û ¥WÁ —»§ó1ÏK½=ÓÙ1“… ï(·é"ñ*å#‹2Õ8݇ -•í§1ïJÁMñ$¹ß%…OÅãÑÇB›“ëLÁçH˯ù=ƒ«hû’×c“VçÉCùs«kß#ëp¹/­¨׆£Bá—Õ‹ŸXÅR›2ûKåI·­Á4±®ù4ÑŽã1«C½åGÅFÍÇáà ‹o­$ß‹;ÿ?ÅAó»ë9]ÑGÍ%ù3áËÅW÷Ç!ƒƒ…©‡ µ!éRÕ'Á"½:ù;¹ ׫:± (Ãý å#õ3ç"Ý!×­¿‹7Ù.Ç@—½ -åT±"×å™Nçé4±QóÃÇ£<Û­™Ý"Ïaÿß)˹ »8ŸÇƒ›ã'õ Ë6ù,·f¹§Ç ù+Å'ïù(³ Å÷"Çm‹L÷9çï -õ!Ý=±ë©WÓTÇ ÏeVŸXÇDé@2çß!»+ûã"í$ÙKÙ…tññ+#Ñß³Ñ:­$ñ<å=Ý5•)£"óÉ+©óÝAÉ6­>·¯ãEŸKχ ¥µs3Ázã½ãcý/ƒ ‹ é:£:á'û @«Ù ç• “2¿ -Ÿ™©· “ç ë08»Ý}¹!©­jË&ùåD…³G¡)« ¡]$­p£áeí7ý ÿ ÕM…~÷§ íJÑ#±*íf±÷5ÿ\¿ -é4—D‰/¥PÉáÁ:ß?ßmåÁ{×é ×ñmG» §ù§"Ë%á,§-•FÙý$?¿•Û8Õb½8ƒç-•P• ý`½6‘å5á5½:­¥ñ Í!/ƒo½±Å|‹G§ˆÇ2í6×3CíñDG£6í7©.ç 1…Rý罉 éLá.ÛÇ×h/Ã* …8Åq7Åå8³ ÏÝ4Çéx×Ý8å‹÷bç -ÿ5©ñDµ©b­Ù@·K™±÷CÑA©Wó·’×#/£—>ó"ã£/µ7¹)Ý ÷6)ç@«7É—?‡› -#ÇE¿+±™ ¯­?­1ÑÇKñ ×6Ëù"Õ¡qQ%¡t¹¤õ‰U­:•Å-­†‘>‹ÿñaÓšýˆߢá&+ó­…§ -õÛÑ•‹ÕŸ%ù£oé)ÏAÍAã !Ù1µ@ÕMÇß«&ù¹@ñ>9ó -Ã%••lë ÷%/¥ó$Ï¿n/O@#¿3ƒWí“;É3ç÷-ÑD·<‹A‹%/¹r-á-CÍ[ý)ór›×2ë>©ÿ.ãÍDç(§ÑE£Å(/¡Ó&#ÛEçÉ §“…“±·3Á[‡:Ù,ïÑ«…tÝ’—™ƒñ¥ëP«­é7Ë«7ß•#+±xÛ}÷©Í*•«:±Gñ8û{“"Sï¡:û=ó•%íŸG‘8á ©7… ï¥E»?¹<¡6…+Ý"£4Ù%¯ ãDã#£ ß8‘Ã7ùqå ±!›xÝ%Çy‘‹ßïRç©H­J§Ÿ‰NÁ•Å ‰› ¥ÇxÏ ‹Û¡0¹ -·Hû¯çOc£ß…Lß!ÿ# -›•É4õ8Ç¡"ç…¡PÕ%ÇÕ=Ý -éÑ!áý£F©»)ëË'Ÿ Õ5Í7“šñv¿Ëa<ýY·¡‡¦¯<­ÏCŸA•4Ã'³‰¡X‘‡ÅfÉ'“wçÑ’Ç›£µj_¥V×…«>£%¥¡ïzç=‰ƒ³ÕŽ¿•_‘Mõ.³nÝ©¡©ÿ)iÑ;• K£‰m÷·‘¥ ký›‰£Í(Ý©Õ! _Ûz½»8­GÅ;c‹"³ç‘«Dã,õd£¢…Œ½!õ×l‹3ÕLÿ -õƒmã÷¨ÃSã"&‹KÍAY}Ÿ"§7Ã@¡nÛ›c“1¥­z«(Ñ‹£CS¥>õvmË2…kCµçAo­pïG“7»0DQ½]Ÿ マ]áa¥3ƒ:ƒ¥µ8·UŸqï—@íhË¡n­ Ó"épiÑÁ!Ã)BÕOÿÃ~iÍÿoS¹Aµ|U¡ÙëA§µ×GIû £ncŸÇíAéS‰–±áAÍ)±vïáeQ·Gß‘kÉáA-±#Çï@ËEKûó^Qõ=Ãa•|½xKÙë>o±C‰Y‡8ÿƒ ÝA×™"“u—n¹+£{ÍmQ›PÍ ówÏ­Ùç’!™9™û„eýb©7³?[Ï7ÙN‘•k¥•ù ³L¹DUç}!©ßy‰o·LŸ?Á.­O¹9õpéû’±ëE‰‰WŸ ‰¡[ƒk½"É~g¿+·!¤uõåªé‡c³+{£y_±3ÿ7ÁŸël×F÷_Eá#ûVÅDQÑ*‡e»T«K©|"Ý,±Ë™0ï!…ñA ¹2kSûEW¹X¡ -Á!I×A½Lw›D¯9¡La—>å@SÙ½BgÅ6Õ »6ßl鯧|õkµn×"…!Í… ©“·‘ƒ ÷õž•› ‹$ëoëm×7ËsM‰£^é—#ÇQË”©ƒ›[íQ­Çá -ù󧡫ƒMÇÛ(DZ[µfÉ…Z‘-¡Vé\«ÿ£§M‘’©ŽÓ‹x½r¹I¿8©()뉙ŸJû7ƒŽÕÁƒeÙƒ‰0¿‹¿±ƒ)ó%±©Å£³FÅ~³z…LËRt׃ë=‰PÇ‚»L»qïÙ\Á=Ëý—&›ý8­7· ‹dÓŠ…8ãI§ÿW•#÷¹ í.ŸP‡­“ Ý ù`ï ‡&¹±O…&ÏÅë?÷™É¿ãKù"Ã8áÇù!Õ>…„¡ï -§+ÝP‘•Í%³± -™<Ï"ÕEÝ`­ ¯ËA¿$¿YÅÏE×-££ÕFÝ …œç6#µé‡=ýÉ7ÇÝ+ñõPé ¯fé û7É Ñ#×­5¯û¿ “ó­¥p‡Fá=ƒÓ*Ý|‰(½tùåÕhÃé¯ µ7—5ý>û ¥, µAó™Qß!§¡a¥4Ñ -éP± ùß&ñ%‰­pù·•»Ÿ/»· -‹á ±§N± ×GÛ Û‰H‡VwÙ#· ßF“Ÿõ°¡Cƒ *­7û4Á)§¥(“& «á?ƒ®©>ó9© Í%ƒ™"ש"ÍBŸ{ó"¡™q½9—]¡"ߣ—Ï›oÙ7—‘¿$ÉX…¬åÏã«vï±» Ã#³_Ù ‹½4ùqÇ0ï ­¯‹!§ÇÝl…?Å7Ù"½Õ^Ñ ­ƒ„ÉB|Á(Íx…Ý&»%‘fíIÝõ4…"¯3Õ3û«Ué Ó%¡Õ„ÅTñ—V•B­[½1«j•'Qã!ùJ­+åb×SµJ¿(ŸP—ûfÕÕ„4ýuñMù5‹~ÁRû4ÛX6=‡”…×PÉÝP‡½\ï­Wí,Q»Q‰>½·\ÁÉxÕYÉQÁJûJÇ•… -Íaß©Q׳¡ •^ƒ<§gõ>íP¿&³Ç)ßV¹;ûLÙ3•a…(ùõѹ$É,éAÃ:Í …@ŸC· ‡#™ -­ñoë±ÿ«¡ª³í;õ6ó:Û?צŒ¯=‹ —u…\¿H-áÑyŸ*¥nå·o¡­µ-ÿ&ÛÙ¥у“žÙŒÉ Ó«õ‰ï²Ùž.ß|ÇŸ•õ›;ù¦­^㘃C« ͤ?¿@7Ý'ÁÓý寿¢ÏhÙ(‰ËátÓ‚Å‘­ -ƒÑQÙA»— …€Õ/ÍkÍj˧ãuÃ%ût¯ í4¡R«i‰Lù½ŸQóa¡†ÛªÙKõPó(¿q¡@Åm¯Qµ;Á‘T‡»Lá•*ÍOÏAãÛ]›û'•$ï ÅJßh½ ƒ\—7é5õÇ/÷aµËŠË…h‘Qù8É­>¡IéE™© ïVçë$ÁKÑË«÷@¥Uñ: -™Ha³vù7ÃM×`éÍa©ùMÅHÏ"µå>rå[õµ É;»?§(‰;³`÷ŽË¥‹Ï6ádß&Á¯…í"·Ï<—李 ¥ ÑÅ7ÏJ]ƒ?U§%»!Ù;‹M™¡%§\Ë© ãM£WÏ8· ¡É9«5aí¡í!£e‘A‰#¥+[­"áï·#±£ -·ÿ*·I_Ÿ:é½ÿÉ`ùg³¡ýJ‹”›>‚÷.ýx•®Ù›q¡B¿VÏŠQŸ}‰ï Û~¡DÅ4…ÁT­ÇpbÓXÛ•·Gë‡Ë„Á¤ÕtùpÉ> -ãz·÷Vɤ«žÉ’×^£@ÛB£?ñx«D¹6ÃI¿……a³±‚áJÍp‹§£ ÿ­ËmÕRçTµ*¥l“%Ǭé -£ÿJÕ«`­Å çmýšÍ–%Ÿ_¯Í.ñ›Ÿ§·+ÙX‹g/›ÿ4…SÙ Ç!ûZË&ÓïW­ ëTå Ñm­¬©å^áY·>ƒxÙ}¨‹ ùq¯œ›5óžzÍ1ù„S“†ÃÝ™r³“íD•‘Ë?ÿ屩d¡ Ç™Ïiý•õ"éåj©D­—>á@”Éwã%Éù3¯ ë!×Í#ý*ý0ƒ"‘«;µñUÑNÍ=•ß Å/í» ÙA£ ÝZå*éÙ -ß‘ -à -ñlÇý?—2Å?É,û9Ù'¯•@ËgÝŽÑ]‰JM³Qcóß ·Ó§{ûs³Ó:ç!±É‹‹ç!Á®¿c¥.ë3ù7Sï8‡•b·™ ûårá ›6eñË É*ã ¡ñ/ý -µ¥níÇËÅFéÿ*ŸÅ+tõ“#“Ó ¥8í“-ç~¥¡é ±³}——õ­ת‰—“eO—·óÓÙñ£÷"õ;¹³·£™ñɜ٭/Ï5› ËAãáUÛIÛEË -½Xo“ ‹ -»8ñåïSÑj­D§­`¹Q˘¥ÍL»$Ïi‰¯š¿ZË;ã;gÇ Ábµ%Û$­û)óPÛUµ3™HÇa—7Ûpû¯B©M‰DÅ>‡sïS«Mÿ'Á`ó>íQ•ÇýŸƒ™cŸ0—lå\DÕšÅ&ãAù<ÅIû§—&µÁ6‰jã•uû:Ç'ÑÍ»!¿]Å•¹ÕŸ/É çJó¢‰,é#±F«{Ë®™צ©‰ÍD=Ó`Ýy“C—2©Ñ »l·‡«á -½3›dÙ§ýQ‡.ƒ¥±oÇwí¹ …©¡Qà ý|» ¥Bµ ÇLÿ Å· -õ—ÿ,ÁÉ ™wÙ -qãåE“)çn—Tµ¡0½@…z³å+ýŸbËC— ¥?•q½'¯ˆ±xÑ…³Ë~Ñ“BÁm¯a­?ÝI»m¥"«]×Dÿa©,Íû½Õ%•HK‘8©PÉs½6‡/·‚å ó‹4Á8Å@™ ÍŠÑ–™¯›‹q÷ û#Ñ1»7ÓV“6—Oµ–ó -ÏÓ'ïJƒ:é÷ £…|Çcó‹8“.…š™›íKï0£L«ÕOŸ&ƒÝdñ-Ç9ÃÁ çëF›ÝÛ•2n™D¥8½iõ ½p·!±@Ñšûµl›s‘ÏŒÍ&í€Ó ó"ébÉpÇI½žÕ…¥"ý°õ%ápÛj­›—ý¡‰‚«‡óCžé…ñ®½9Ù¬á†Í§­é+Ýu·‘¯«Õ †©4óSƒ!ùT‘%RÇœé—áo÷Œá1ßn‰ -‡¹Ný¡¢§<Åw¥Ãx©íQå#÷ˆ*í[óUŸ)ŸF÷l¥­“ ã‰Û7—Ÿ¿Ž—í¥—…G‹=¯ “jé!·W¡pÝYסû‡ó3ÍgŸ4ñf¯‘6ëÛ9ÙŠíRã³UŦŸKíÑÃañIÁ5ÿÉ_ÇPÅ‹½a¡ãKù÷•» W–‹’«)¢± ™—¥{Å…áV±qã•£Dû$Ña‘ ×$•‰“ˆƒ&ÁI‰“áÛ”‡‚½¤ÓF¹EkÓ$×\çDý˜·q)Í'³yãF“Ý_Ã,ÛÝ\©J…i™¥…ÇMÝ û.¿y±—ý(¥G§Éý@÷”E‡;Ó ‘g“2‰‹nÓPÝ™Z÷ ×{¡“F÷*ÛiÙ+§%½‡×(c‡!ÓŸï ýA­>Ë=ý"ÛJý&ç‰fùÁgá3Ãï?—?•Ão©+Õ@§(áC³;÷:ã6¹TÑß0ݵEó(§'ßDÑ(¯*‘‡f¡xÑ%± Ý1Émùݧ3û/ÿ,·DÓ›n7‰Hãã8ëjû¹…xÛ(ý5ûC&ó©@ñ-ßÁwƒ™P›šÅM©©ÿŒÇ'‡¥[ךÑ›…‡j·d‡3™Û{³W—¯ÓJeÕNçWÑÑ7¡ ‹°á«³Bý7áfç÷™§ õ*ý_™`!ÍQç’õ-/¿³’Û Ó©Ÿ mÏ"© “:å «~ÿuÉ™%ýyûaë=±SÛ!éšå‰2á6ï+‘w—9ó í’“IË8׋#Ýo³ É(÷¬ÅrÍ¿M©~·"£¨‡5…3·¿óBñ× -ù—vË8ûe‹%ç -׳ ‡^©;•{Ývó‘7ƒ™Ém‹ ¡ŸÙ‚¹a…©«³›…Ï»!#ó.“ ›„5§>û÷Õ ¯»s¡E‹c¯@§S­}‰„Ñ3Ù#Õ+ƒ/Ç!ч­a›Dç_k§CÕx‰¤¯ ƒoÿ7Û¡÷ÉQù‡¹=¥“Ýn©¯4±Õ¨Í9©hà Yƒ5É¥†ßKålÛ©û×r‹aëÙÙσ`‡³³yï÷kÃw— ¯#½§Ï ÃN¹{“ -‰¥ÿLÙ—a©@ÃËálÍ©O¯Ÿ‘$™›d‹ ‘¬…qÛ8ñ¿œߪ‹9¹]ã6k£o‘–÷•”ù‰)õ Á@ã -áIí=ÍVÉ=ù »ç¡‘r•#ÛÙoç —ÛhÍ+û -™=ç6›¡qÓ!ŸÅ!Ón±où9«8%Q+ñE9µ#ñ ˃C!Õ“ Û%Ó+‘#•&¯?³å7Ï ÕƒãR¹ -‰<75«Dç'›$·a§K½ã-Ó+Ù@¿0‰ ­'-ƒ&ÿ7A­7½ -Û0•-Ó6Ÿ ó5ù?q‘½"ÿ‹ Õƒ5#ÓGñå ½(§E7©·!í0Ç@%•Û¡"½%/ÑF«"ÿ­M'ãñ0í3Û#ñ ¥(ÏëJ=‘9½ ùe›“ ã-©8‘@å±MŸ -§W•#‰ï±É@µ,³bá'£KÍ­@«3¥é;›A³ µL·0¯ “*Áã5¿ùgýÃ2Ÿ?ù!»5¥Aù§&™Ñ:×+‘Që» ÇWù×T©"Õ‘)Õ—8Í ë"÷D‘4•?Ù!Ë)ûCó ¹ó$émÏ ëCÑ ÛJù/Û×ßDß8 ÿPéAÏ!í9¿Ÿ‘…íTˇ!‰(Å%Ï`ýÝ ¯»h¹(ó‰ à -™ßR³ ßùí)Ñ­9— —»§.…"é=Ù-“#¯Ë í,—M»é ‰C%¥Õ ½*­!Û÷<½ »+ù"ï§8É0±~­ åm¹—¡¹~%…ù<›ÕL¿§9›í&/í$Å6ë<¥ -­L•C —*ƒ&ý©E¡"ß*Ý­5¡!÷ï8Ÿ Á)ÃÑ+³ ›&í ‘"ƒ0ÁAá“Eý9%‡ã:!Í@ó‰#ë!—@í‹%µ -ÿËq÷­aßù"­ÉÑQŸ^•(Ñ»sß­Ñ%c¹AñœçÕEk©-á"áÅ4×ã¥uù5÷BWÏ9‹M—Û6“;gå¡Ñ×<‹5s·é>iå µb°á§g»mË(©ÏR¯[ϘÕeÁEOƒý`¥4eÉ?Û Yù@QõO‰g±"ÇWÑj«ÙWû:Ó÷KÝ#· a÷C‰”Õ'§\Çc‘~Ù‘RÇ>ƒß/ëV«A åƒUõ&ÿg‰‹õAI£ñb—ªÓ%[õ>Õ:½G3ÃDŸVÉP×›ÿ4ý<íië1Uù5Ç4¥½aé -E“½xûcíŠÏ uŸB¥VËV…-ûPó¥Y™jÅ(µùQç@]颓5#ãx›²½ ñ…m‰Ç^“· oÉ@Ñ…—@;ÕÑn ñ8¯±5E?¡;û+‰2ï3ëÏ/íÑd&Å5ƒƒíx¹„‰?ãã ÝcűÓBÏE­!§;½¯­g¡*¯yÏ¥Kƒ3¥8¿ËÏý@§™ß+»Cm£å.ÉL]·‰ -™7÷£DÑ Í ‹8Y£²¿B;Á:©ë"Ï ³ƒP«'¿){‹ßg¥g Ý?õÙ Ó•±RÃe»=ï'Ù Só=­³ñbÛA£×@ÛÝ@ŸPËjý,‰­8YÃ)Ýe¡ÿkƒdÏB‘6•‹¹ -§ ×raÝÓåS A¥D§ÝT áõ>ãR·:Q‡•¡ïAk “gû±ý›FÅ"MÁˆ¥1ÛJÝ!«‘ ­kûAÅ„±Ó6Ó5_§ -ûPW³„·2»K“ £Å|»ž“D…>ËT©I‘7»WÏ¡lí » Ÿ§*µ……‰![§5Ý<“Ý;—«çT‘¢ÿ—Í?É@é0é8W§#‘»5‘9cÿ˜É!‹A[ç5ýMƒ7‰XÓe­D×ÿ›…–‡1D¯ÿvÙÝ“ç›óo—?ù ín§ÿn?· ÇA‰eÙ9Õs‰ïDÕœ¹8óm™GÏAËA¡ß!ïA±Q…No½V½VÝ=ß4U9åaëz™kóµ8R•Ï'› -Õñå‡Ñ -ñYÅñ"Õ*½0¹@¯¿ AÝIË:ÉÓ4…¯"×¹õ £û=¹0Ý£7Ÿ¡S—‹Á“ÙhëÍ/å2û>¹)ÉÅõ+Í?¥Ý&µ—¹ÿ¯‘+»¿éb±³)¹‰ ¥Ñ‘(í¹.ù:™Ñé ¥3Û‹§›)_ñ-‘Õƒ‹aãÉ ÁùZ‘Ç«8—)÷ý­ÓÅ Ã&Õב Ïù©A×ɃßUÙÓ Ù(™µë*ÉGýÕßå½ ¡Ë)Ññ?ᓱý×)ßZ«ÇÇ,©:—ó‹¡3ß6ç]Ý1Çeá™)÷ ›3Ÿ.ÑMË …Ûf½)­éb‹@Õëû%™(é ›·3«³1»÷ÿK¯Û)ËûDËÙ&χÝ/<ÇÙF™'³ ­Ïµã¡XÇ߇«`÷é4“é£_ùl_ùYÍ“sýᇃ -—NW‡å ³ ñ•Zƒû+‰ƒ —]·5Ó†»«·ÅçÃÏZÇדåû瘿˅ù•QåQ ƒí'‹0‹‰D¯Š¹ûvËN¹½¥ -£Ù½n•5‡/ï ÷±&ÃãóíY¯§ -ÿ%…#¥*å'×0õ#‘ë… ½ñÑ Ÿnß ù÷·±×.³ ¿9;Ë?§Åóß?»CçÙñ:ñ¿Õ¿0Ÿ+¹½ë«8Ù¯$«×@ý­„÷áÛIû…‹ß§I¥Íbý Ç1/Ý'åJ§(ŸOáÁç:áH—‡JуíïÙKµ'«¯‡G•Ù÷ó¡Û§?±EÁ¯ï åIãÕ!³ …\ɲû±¥,“Eë˜Ç;Ï·#÷ÛaíX³±*‰Ù#åKó -ÁwÅ9µ=óÃB•`ÙÙ »D› Å3¡­W›ù9õI½#Ÿ£‘ÇpËBÙS«ý•m±$çÑ"“&û;ýó§H¯ µ³!£¹©Í\ í!ßïT·F™!í µ'ÝÃË -¹³TÃ&ý:åÉÍ6½ …a#ë'õ» ·Çë•ÿ‰á‘W¿ÕEÏ-±± ë û9¡(Ë,Û%Å%à Bé4ʼn‘S© ÙÓ)íkó­"“?—1Ù(ÙÇCÃ÷¹¥Ë+'á"·6Õ9Ÿ"•0á ù"=¿%¯L¹”—£#Ã¥‡@Ý(ûoi ¡d‘ £ù‹§1ë?7«©‰K™ áK§‰=…™ ¿I™_¯û%“©8ñÑO™Áx± ó.Ňaí˜ÍS§!£m2×NÇdÝLÑ›³kÅ­2ñ,×`ñNÛÃ’٠ݥg‘{£Re‘Z÷O—ÓNEñÛYÅ©7ŸÏ>ë™Ã³7ËÃg‘ã/ñ6ÇိÑs—÷‹7»Ýž¿³¿^å Ñ2ã0» ½Ùba›9‘ ÉM¿šÉ$í"“'¹y…§ ïUá‡YÏó -ã ¥+ë’Ýã/ñ·E6£6‡"™ëy£Ñ…{û 1‡7Û£:«ù¨Á+ƒ ßšµ -•=ƒ#Á~É͉ۋ·íW« ÑŸ ó e‹ ¹9Í(¡cù;ÙMƒ ÿZÁ%•Õ’± õ¦‘B‘ £"ë+÷€"Õ£7ÓÇ’“1ó6i•#½ ‹ çù;ñ±7ÿmë¥4¥M»˜± ᘷ é÷…u·4û©Ùvé5ûõÃ5áL“Eñ8‘Ã!™˜× -û<Á"Ï~‰'¯>‰ÝH¹7—%Õ{í -Ÿ—!ó‘½2ùLµ>ùA³\áUñ~‡#Û˜³ ߇ »r£7õ0å8ù,å Ë8ÙLÓÓ’Õ"­|¹SùóŸ˜ÿj›#¡lï ¥jÙ3Å(§n½cÕLÝ!Å-¡8Ë3ÑŸ}Á0Ý8÷4¡Õï §a¿ï•¯8‡5¥t¹4‘#…ñ]Õ²µ{Û…}5óÛ Ólëí>ÇÓM½k£Ë‹‰'é ã'›4×c¯±@í²é[‘7Å -?õª•µA»nM×ZÑZŸÛOõ?çRí ƒ%Ë¡4û]ï_I¡P·;±‹,©_›¥8Õ S¹hK÷ ç8Õ »"ýpO7ÿí#»!õAÅ…±Y‹Ëdßiã$“[Á¯¹“që--ƒ*¯"³½7› -¡±é$…A»Í6·7ÙJ]‡‹§Dá7õUíW÷#ËÑJc³$Ï“>©¡ ¯8·ÿm)Ù90ç¡8›µ!‡ a©pÝ·9kéd÷ ¹$[ùl±]¯AéAù›eû#…JÝCU—Y¯9Á Õa›!å¹ -­Û6ïAñiŸ›mÕ -eç[ñ· ã»{ǯ‰[õ*ŸmŸ å"—;¹q—Ÿ5ÁDûÙ"Å#·"¥qÿ/¥ïý|o³ c¯ñwÉaÁ…»,Õ<‘½*c‘w«tŸDûù9ƒ é7ƒn‹8ýo¯SŸ‰CÏWß6ÛéSÓ±6WÅ¿S©9åb¯T¡ 9û ûSÓ?émD™/[»LÅ!£`û&ï·1ß(«2µ#‘ Ïõó!ù%“Q£!ÏIíbñûZÇ8ÛJûËS›‡×9Ñfý1§0›&©·¤¡PÙdSùyÉ7G‹ ¹[¡ ß -ã g÷%¡_ç!›A© ݹ}©–… ‹6¿ ÷(¹bïc«!¿5ç;‡ÿ!Ã"ƒ°§§zg‹Nç9© 9½×a»Á!½¥Ó ¥‰§ ÷9_••§ ½‘«™aµ—µ7ù–£ÇbÁe·e…‹T •#§"Áû?± -ý‡ý íjÅ!‹O·5gÕ§J‰ÇÍ µJåA]³ó#ñtÓç!×wñ×5­ Ï9cËÓ§©#·{_…moûU™ -M«“n£N³© Ñ9]ÕlË_Sù$á;í+íx/ã2eÙ"›!¿¯µ‹_‡ ›£0uQï!…/û8Oã(Ç?W×$‘©ÏnÓWõ•KUë5û“Õ‡Í|Ã-™@Ë -Ý6kÑ&Ͻ9•/— Çv[‘[ió?ÉÑ,ù§¹n͈‡)O…k¯ ¹Ù¢³†Ù‘sËá ¡“·]“‰ÝÇ~¹fiá Í8ï”ñ/ÍW“Ë ‰¢ƒ9qÅ!ß!çi¥ Qù‡-É#S• -É7×™çU±PÕ_ƒýõ”¡šßù—!Ñ(·§±ƒ É—0ÉRaù »Bá8i¡ ù•·R±S­Ùmƒ —1a‹ -ï8\Áž‰ ¹…•SûŸý ÝFߧ‡k5‰%Ý/J• å3—c×NáBñ ã:ƒù6©£nå£ —ß#WŸm‡IÏ7û¿ù'ÕÃç‘Ïÿ« ß’ßw£a×#á ýq¡½§2•7Ï6M¹Œ­%Ý!ÑQk©²«f#Y«Kɨ·’ͱ‹i…gû£#‘ƒ É.•å•xï-é.‡­µI½JÇÍ$³,e­ó5÷¯§ŸªM½Cïkã _7Çe×£WÁÛω©"_­nW•§5¿0‰¯å]Ÿ¢÷¢ÇÓ‡Ÿ8ã Ï ‘Å·9¥oÅ2¡¿°‹™‡ï7VÁÛ×7 ¹ªí¥"×pQ÷jݳ8µ ×™B›-K«LÇWå ë°¡Uã!™’ï -”+ï{Så;õj‡UÏ ]קƒ]…[ÍÓ6Í -¡T·Ë8ó _Å]Ÿ[mÃ9å›l›,• m÷‡ï,õ— oaïg÷m‹×ëóTëeÇ×¥D‡DÓWŸŽÙj‘cåñõ -ÍR¯ž¿[÷7÷‡Ç“µó|åOÑ„ñƒMçvGËY‰‘yŸ -ç.‰!Gßù2Ãé%_‘£6Ç=ß—9ß3ƒÇt¯j£Ã¥ùc¿JÛW÷žƒ‚ÿrAµ#½-٠é Ç8¡"Ï w½m…Ycé^±!Å¡™'ç£6û½„÷œû…Å oÙË¡"õS‘F©2ãÑ"k‡*{ë¡’õ®³ƒBOñ:ƒy­;ó!—#KϤ±)£Dù…4¡5Ùï#?×m¹Qá¯"“Xûõ¡9™k¡¥×"³E¯ õ8“ Ÿ;鎗GÓÛ`»5ó ]÷¦Ñg©Õ -M­[‘ù!û%k‘Û'íbó -¿­í™8¥i³÷§z‰!¡žß7‰N©/Sÿ•«£Û‘ÉcßFK‡ ˜“ ÿ —"e»{aƒA“]“©7õ…¯®Å—£Uá-džÍ«¯1“Wk± µ7¡YÃn½”åH«½8¯ -ÁTŸ;¹‹÷!µŸ…b³7… W…f¡ Õtcƒ ¯gÃ|¿ñï -Û ÷½&Åm_»¢Ÿ ‘lÍ!¯)ÓQ£Dç7·,Ó£ oqŸd“Z™¹?™ Ñ­ ÿq_™aÃ"çz½Û@³»6‰¡µ­“FÃ!‹ ý»°óhÝ û:]‹…« á3é:_·ƒíLד$U› ¯iû"ŸmûÓ©zUÝqÛFÕD­‰ñ -•©ûë »‡QËg™#¯"Ç)Go›#›’Ë#·"¯Œ(ƒ a½wÛ*ßYë™Ùsã>½<óƒ"ï“Í6Ï;ƒ(‰_ùãEU¡8« ï6ë_‘p3©"½ËÅmÏ•‘½só@¿8_—‹÷š+“\kóWÇAã·Y·AéO÷¤»yý8QÁÅ ùyýA“7ÿ›±$}ÛÃA¹£q«ç Ù« ¹/Ç™<ÁÛ ³'±ïrý£¿™MÓÅ 1gçt·ß¯$±NÿŸ$¡­jÙ0ýùÃ,‡"éñ9× Ç÷“Åõ ëRõ©ó45‘É í“ÿýCÃ6M—ËóD·"¹­ +¡› ícé ÿ:“«4¯lÃ1ÿŸïn‘«ýeÃm¿7½/Ánõ–•»Oəǧ‰²¥(é|é·“ýV—=ÿ!ƒ óË.á¤ë ËW`·³o­.õÉ*‘ië+á³.¿¯sÏQ“¦bá%õa¥;õ -÷ù0÷S½Ï(û 㻣(Û(•!‹ É8-Í#ÝÕ<ùƒó•OÕ"¯pƒ -á\·3±,÷£(•EÕ0¥]—)RÁW‹ÙTË—ç8‹#·.“ís¹1%«%—µSßq¿1å&•Ãƒ“¡Á%£ -»Q·Z«šÉU÷“\ýx»*‡›Kÿ¯ŸW¿‡ŸïƒË!—‰Å8«2©’ñB©a¿ŒµCÛ Ñ~Ù*Ïlñ‡Ç5ÉJ¯SÓœ½b»¡í6±шÍšçM±:LÉ:¡Ÿ„¹ ãGý©¹¨Ó¤ãlÅd×­ïm£tçL©o³>Ÿ ÓÇ…·4‡nÏ%›~Ñ9Ý -å-ÿ)±Díïpñ'åš3‹ÏŸ•ª³ÓT]³o×&˳D…Å̓õWÿ¡©¯ÿ‘sûÝ™Œ‡q¹P« Íu£ÑR­σ­rŸs›­Ï„­IÕmÕ<¡Ó[£Ÿn« ß ƒ›Hó[û7ÕÓu“‰·£›±7ý¯Ùzù‹ë£¥hÿ>É©yµ”ï@¤Ï9‹Ϫ/*õ@Ë8Ãíï"iÉ­›NŸ?Ó@ý Íų:ç7µ© -™•¡ýríñ ×Ý[×6¯ Ç$Ýmµ û!‘>8­ÅW›eɵ»ß9£BóŸ>å8‹5¹>…:Ó ‘C—5¿S©³#‹Éq£"¿“s×ë''¡@óu—/•"¥på“4¿!9_?£"HA‹8ùPY…¯ŇYŸjŸ Å™‘ù™"¿,¹!Ù_Ù-5¿8µ(û WÑlû韙yƒ[¿7ÿœçÇ“”Á2÷7Ù)z¬K]Ñ—©Ãe ›LUƒÏ Ë¥ƒ™kÓ•§m÷ó™2Qã©!õ…P‘!“KÇ€Ñ ée£BÅË’»¥‘‘^‡ ñhåŸËó0á¿e±¯Ñ ×—“·f -8íY£“ -áŠû°…ù$·{ÿV£L½v9Ùnó ÷)¡ñVÛ ã=ÿ é‰:ãC¡ -û¿ ϳ|É…|ÇNÉië"µñ}«[»"ï(¡ Ÿ6§P½M©7—ǧóx—eáM¿šû áN¯7Í Ï!Æ« ù]¯ ÙO·!ÍY…“5ƒMù Ó!±’É Ùù7×!•7·lÅ ëZ7Åí7Ëe¡!Ÿñ™Cµ9¥ ÿë!±× ÿY¯ß‹¡#Õíý]é:¡¿Œ·$ûyýEï7£Çµw¿7ˆÇ$FÕ¹ ‡7á`åã…‘…·9‡£9‰7‘Në8«3½NÑ#Çl§’á—OÉ!™K—7ëañ û,½÷`å ßaÿ £v…9§•™ -ë9ù;Ã9Ù{•Z¿#³b¿8¥<ï -‘L½5ë\Ñ m»!µµ5÷uÑ:0ÿ Åg‹¯J7‘Sá Ç9ÿ ±W… ÇV—_ÿK« ï"ÍÃ7é"•?×ýSÑ”¥ˆïžÑn»™é•Á§›á$•¡µŒÓ0ûD‹/÷&ß«6£&¹Ká ­ï¯5÷Içý•¥¡»Ëù@¿Ó"ÓKƒ+÷gï ¡/Ÿ ³%¹#ën -É‹!÷K‹4±/¿¿ áCç$Q× õ³ -ëÓf½GÙå -·ó£!Á;—ïF“…Ña©¥#³¡í@—ËDÁEÿG·‹±‹ÉgÁ½$“7ÓNã Íjã!Í#ï%ý+¡׈½ÿ¥"Çjß" õ€ë«_Kû5ƒ¯Z¡ ݳ é ¯Ž»ëï’ù@» Í÷•¡+Ñ 7ƒ ¯_…MÓc» ™zé89’ÛÏ!»eïAëï™Å!§§G÷;Ù`Í"Û‹Ÿ›7ÿ¯$— -\©8Ÿ¿“ÏK½7ç)Ñxéaï>…86·)ûzÕÑ­z"2Íçÿ6ËÉPípÑ"+“#ýÑ9Ó§4çVÛ ËÝÑ9ïZ•,Ññ©ÅqÏ"$Ó g¿8×w™7¡é‘…&z¯¡¿ÉtÅj• ÷6ë&ß<£jù ¯+ɹA‡ §®ýÇ6³$»!ñyŸ˃a¿8¡jEï¤Í„¡"Ë1—é¯%Ó{í_É6ïí /ƒç|×EñC«:Ãý=ã¨Ï­w›—¡Ï_-©ÿ›ë(!ï$•Iƒ7÷3—(÷„å"¹@5ëGõ<ßሹ)ó!¿ªËû ©H±`ç™».Ñ©ÙGaû¥+¹Ï®§¬^á‚Óžíà -ë<ßWë³—ë,…s¡—CñW‹1™uƒ-ÃS‹OùC߉Ç]ÿŸf‰“!¹õiÿƒgåóV‹'±Í!Å)Ë5ŸlÕë¹­‰Û‘ÿ#Ís¹ÁN¥‘רÛ>ËOÅXí-ÙdÕ ½5Ïfñ"·6‡Uï#«4¹}—‡4ÛPã—Ñ`Í ‡o™§ßkË ¿w…Ží ×Jë ¿¬ñiÁ “q» ¯”¯~Ï<ùcÍž­q§OùN…@ëå#óï[óL¥b…²ÛvËÏ :³§ÇÍ ùÙqõsá¡k¡’¹‡Ý±¨­OïN×x©*£ïëY7ÕE£2ç&Á€Ùõ‡éj™4Ãzá–ñ²©ë;¥£]ïÅ­Ï”µuïí>ßQÑë ‹ÇF×W‘™·%í°­fÛ­—‡·9íªÑ-çBݪÉnýc¿ù{¯£\‰®¯ ó“ÿy¹ ƒ2Yó*á”Ë›&Yûm¿G¿®™¯q·*Ũ‡ ç?ÿŸrWûM©ŸkUÃ#—o©±Q­lÁ™&Y׉ÏU€c‹J—ëoÉAˤ¿pùçû”á“'¿o‰£…³Ñ1Ûˆói‰½@uã…™–Íëƒ[µ&«_Åc÷ŸóÁh›+¿~k‘KÙ²õ)•y™>½R¯–õ7óuëc½»H‘o¯°ïD©Rg¯µK±ÅIÑIí1ÅlE§#ÕjÇ-;í¯›:å1›±£6‰«uýz¥õ£cµ6­0ùÕ#OÅ¢‘E…›-ËDƒÑ)·C÷$‘ Ï‹ï—ñó”¿3멹`»tå—™„Ï5Ñݲ¥f©sáãŸÓ«5±.£HÃËi‹/Ù “ŸwíÏZý@/›Á¹>ïa;9£ÛDÛᧅ›Ç·ž»“£(ñdÑ-·-m÷%ƒ· 韹uóÃ/“J5¥9‹Û4™3Áw³'›Gƒ2é3½ -¹R¹#ûí"#×É©tÇß2…ËÝ=µ%Ûñl9Å9½¥_Ý9/<—í2û1§ 7­œ;ÃÕ“pã)Ãc£3Ñ Ù•#­¥ ¯M¹•Ëµ&?à ­¿9§BÇ[ûNéõR­‰w‰+¥7—°•¨é˜·û–ï=É5§L³°«;ï -±Ñh± -µVŸˆ×‹_MŸ,Ýr»™Ý ‰ ¯híŒÏO»­ -õ~Ù"“.ý¬›*£ -ërƒ$³O"óœÕS©Ç#ó¤ùE‡M³"Ý÷oÇ« ƒYá3ý8›ÏP¿>‡ƒ«O‰b •ý-•]»O©•mñGóÃŽ—L¿ŠÍõRŸ‘xéÏMÅéfµ6ÑCÝŒñ— -“Y³¢ëg³µŠ­…¯û‰Ÿ¯vÿ¹­E㬠‡@÷‹“3½±P§¥ÍPË"ï%Ÿcç%¯6Ï8•ÝmßC± ½‡Aãb›9µï¦ç\ÝLíM¹«Í]Ë7󆛖›‹:§-ù1¥oå ëS¹œ… û ýHå‡$¹Já ›gà Íxù ÿPÍ «”Ý5ë@¹ ÷ßMÓa™±{Ù&å8Ñ"£žßT£ Ÿ!µƒt¥2™6‹ Ë^ýtó6‘PÅ ™$³#Ÿ³Å3¹»—9ÏSß í(Ûp•“«›±1éŸ:«Iñ ßMÓ€·!¹ížÕoß6­‡ ±k µoõá cÓ û ÝŸHQ…[…ß0ÓSÕ1ÙC¹­ É -ý9{)ý «k«×hÁ -¥EÇù9¡ _•,¹!ñUù -ÿ5YƒÃ9g¿máD¹‡(÷å8ù+Ùß$§í÷—*ÉEaÿó—"á -µzÉ“ýžµšÏ¹ñ!ÿ'cý…•Zƒÿ#‹7…ˆÍ ¥I½:1‘#‘Í›¿Çécû"¹zï8ÙQ‰ …o‰ -ñ5×ãDý!ë¥ÿfû¡µd‡Q›#õ2¯¬™¨Ÿ-å"ÅJË ©9ó ×@Ÿ$­"Ÿ¡(ÝP­$ó -ÿ8É%Ó ­:·9‡4Ç ƒ Õ<±@ñ$õ‰99í#éõÏ/ÓÇ)µ#ÉO×'ñƒ ïNã÷<© ûAå%¹"(û…¥×L‡"íÇ4?ñ3¯Ï ×D»+ý$ã¥6C»GÇ*Ù7í×lûÇ -Ó'½C¡ Ã:õ ß)JÇáól¥ µå7ÛõFá« -ÛPÕ>…*¹‘ ý6Ùë±\›ÿAÛÁ›1¯ -é4‰?4Ó!ù ¹?ÕE³³7ñ8· Ó(ï©?á “©)ƒ9åë×#å“‹r¯± Ñ­¹8Ë%÷#ã(éå8·@µ © ï -éOïÝ4¹L©6—q§£Ÿ©$‰FÝ—r£>“rµ"‰E‡.Á ­Ñ&õ!¯Rí¯)ñD"çhÝÝ•"ßnë‘Yý ã:— ŸJÃý!ÑPµ -Ý«›0Ñ·¡‡XÁ›íS½¢¥^‡»ÛëEí‹9—•|›§«1‹Ÿû§vÇnç õ …7Í>ûLé*÷Û/‘"¿]× -ÛnÑhÉ}÷ ý6ÕqÉF«!ëxÙ ‡+ÉÑëDñq¿dý …6©B³Ƀ -å9¡ ­‹I‡’ÍU‡£‘û"Ñ#\ñ0ù&»£¡`™‡ß]9‰d£ -ÙYÁ ó½I‹z«?Ï@¹!‰©IÿûjùÓ’g“(×|á²Á]Á&›ñŸË ›I¯ª½lùvÍ3ã\·J©B£eÉõ ç3ŸÑ å&ÅK±Yóé åV韓ýÑ¿­• ë;à -±6³µ9«2óI¡+ƒ"ñbùáG‘®ù)§d•£å¥í©±ÝOûP±c׋Û -“lÍ"‘*Ã]·ˆ•Áiƒ˜Ùf™m“™¢™[剈ñr•6 ‘'ƒzÉu±¦ÃZ‹€ßEà ‘ˆ‡,™w¥Û³Ù7ýK—yá*ó¬÷%±Sùá&ÅÑu›÷‘%‹Eï~ÓGñS¥ ßV‹,ÃÙJ©K‘tÁy›ÙÉ0ƒ³2µDó‘Ë9‹“—P1û Ù‰©c¡ãWÅhå'ÏÇ 5µ§ÛA¹9«—õ ƒÁ%ñ ñ­3Ï3•5ƒ íÛ ¹*ñ1Ûœ©mÁ…™^Ýõ1sÙß&ýùçÑ7§EËEÙ ñíÅñ3½?…BÁ¥ -×Ç|ë ¹Á'ƒ.ã Û3×™ïl'…ý óé}½íݬ“Uñ#Ÿ!ý}Á‰©"Ý… 5×!Å?»Ñ“Š£Iÿ¦ÿ§ÉÑ7¥å€é¹ e©fÉD‰FÉñ9-½ªÃ9Û~»¹Š·‹9Ëß@¡¯§õ© ¿6QÕA«"ï"½ˆ»<ÃP‘Õ‚!­6)‰±-÷{á‘5Û¯¨Óµ‰!ÿw#ëv•\¹eÿ¯xÍEí…·SÇ>« Å!Å7‰7ó<Ó>» ·‹#­D‰‡LÙO­ Û;6‘¿Q¯ Û:Ÿ”™å)õ ½_¥;‹kóë •<ÕBŸß8‰ ·RË嫱Q³>ÿ©5éA‹;ã ½DÏÑçAµBõ©Wç«ÕAµÇL¡]Õ3ÑF× 8±!¡IŸ ÑDσ*·:×3÷!ó8³9ñûGýJùO¯•#Íñ ¿P½*¿Aá—‡ »,éP­S‰“3« -ÿr¥à ÃgÇ!ëW÷xÃ"áyÛ½ ‡eÅã˜wŸx!ƒŸ©Ÿ Ã:ïŽ#Ë ¥m¡!áŸ9‰kÃ^Í6Åz×3Û©"N¹:³‡ãjû4óÓ§µ½“ÉKï_Û‡¹!ŸSÙ!ñÙ«ù÷ÛZ­7™¹“ÃÉ7ó ïG­‘"‰0¥WƒõJù6Õ‡Ù£™U­—«H©"°í¢©“¹­‰Z“A'ÿ•&É™͆ÏÕ#©™$¯(ňçk»+“z&ýˆ×QÓ|Åo¹4œ§ãÝK× «g3·iëf&Ô©Ó=µóvñ) Ù†½Ç&™Lëˆåç“NÛ6É -•!Ÿ· ™#…s£g—>ù·"»S¹Aå<³/¿ã}óó å­*ÇL‰4 Ï™³IÉ^Õ\™y3­vå ;N— -½¥ ™¦›!½"Å_§R8÷UïÁ,õ0‹ ×Ç•á᪹Zõ‡zˆÙ"¡‘÷-›¿©n¡×@É -鬟 Ó1‡y³:™³çŠ¿‘ÿ 塃}¯eé ‰œ£ãiïœÛoÇ&‹8&Ãí ñ ß{£™ÍZý õ‘.£íC×7±»ÏÛ[-¡Léoà -Ó.<—iÕßtÕfó'ÿq÷†¡­b›/± -ÁSù†ù¤é'å -Õ~˪Ù¥6¡^™gßË3±M‹RÛ«‹[­~‡V›8÷Q»AÃGÛAý±`I×]‡­•"é8µ$éyÑ[õŽñLËW÷7RÙD«Ë ©ù‚©„1Ñ+¿!õOE­i×õ4çÛS›GƒW•N™R½Q˱Mß-ñ€…jÑ<‡v·=¥õ`™6éT‘&é_Ñ Õ -×S§"ýcÅ‘]ÝWõT6…Gµ ýFõ=™(¹'¿ù#ÿ†½D—³{µƒ‹çzƒÅ­ ßS¯•‡˜Å<õeµR‡%Ùœ—FŽñ"½‰›ó?õh…k©&ÛAå$ã)Ùµ5ŸË4ç*»‰oÃ\Õg³¡GÕAÓ>íŽï…“où Ëù‘Ë érËšõŠ¹…M·!‹Ý{±Ûœý*½@ÅŒç‰ÛOßÑD§8‡2ÿNá5£uzÇ—<ï ±Ï~ᬭÕXß3¹Då¥'çj›#»cñ.‡Náí¯[³eé"ëŒã‡uDÉ‘óFµD³*½y"Õ”Ñ@ÏVÿ·#ý‹Å±«ÇNÁDu‘"×z™Oå@ÿ=ñ™±–±VçÏ¢©©1ß«¥Mµió0åQÉ0ñ¡™íUÑA× ×ÿ/¥ çzç1®Ç«#Ñ™J§eÁ§„… ë -·@¹ŸÑ49Õ•ó]ïýlï Ÿÿ0Ñ+—™ƒz±=Û -ÑvóE— ¹Bß’f‡ý:ï^Õ7™ ­eé§Pzÿ?ÍHs!³»V‘ÓCÕ6õz횇— Ý8 ín­Ñ8é—é™v¡…É]Ï #£Œó'Çm$µ‹#Ï •D‘¿£!“€©ç*±&ׇ&‹Ié0¡±$™$³Û"Í5ƒX‘eí/ñÓo«#͘Çõ3· ß—³ ýÍ7±CëÕl÷6ÓK“bÕ÷;µƒ‡9ù‘³NŸ» õëwñ£!–Ó -ÏL¯ ¡oï"ß -©tý!Ïpé(ï@Á8—Wà ßß6½+ÍËç‘¥ñ3¥‘0‰&ï« É×4•5‹é½$ý%ë#•'HÕù%«£…3ÍÓ÷׫[™ãï:­Z@³~Ù/Óí)ǃ&Ïõ·³ÿ)ùP³•-µ;ÑÝ&á=Ÿõ…ÍÙ¯!³ ¯Rù• õ1½DÍ0ÿ »ó­&ß=³Ã‡‹)½3¹§(Õ͹ “Ç›>ÿùë'Í ï •µ7õ9›1‰ Ó!‰é#™™ã“$“!©'é%¡0çññ ù÷Ç&É(Õ‹í å*,ùJñ³&ÉÙÝ(—ë ‰Ÿ Ÿ>© Ý!³ƒ+=ëßï%ù Á -Ëדï<ƒÉ -«Ë³ ͨ…tñ¡¯ Ï{Õs»hÙ ‰°ÿBÑ!×8*Vßçá£&‹«F@ƒ ÿÿ|… € € üÞþÿÿ0€€€`€€€€€À€€€ð€€€ €€Ð€€€€€€€°€€€à€€€€€€À€€€ð€€€ ‚€€Ð€€€€€€°€€€à€€€€€€À€€ð€€€ €€€Ð€€€€ €€° €€à €€€ -€€€À -€€ð -€€€  €€€Ð €€€ €€€° €€à €€€ €€À €€€ð €€€ €€€Ð€€€€€€°€€€à€€€€€Àá ñýÉソ -¡ ýᯠ                                                                                                                                                                                                                                                       ¾/ÿÿ|îÿÿ0ˆ€€`ø€€ë€€Àó€€ð뀀 ø€€Ð’€€€‚€€°‰€€àõ€€ó€€À€€ð÷€€ ý€€Ð耀€é€€°â€€à•€€õ€€Àô€€ð退 õ€€Ðô€€€ †€€° û€€à 퀀 -€€À -ˆ€€ð -€€   !%   & " !%                                                                                                                                                                                                                                                       ¾/ÿÿ|îÿÿ0ˆ€€`ø€€ë€€Àó€€ð뀀 ø€€Ð’€€€‚€€°‰€€àõ€€ó€€À€€ð÷€€ ý€€Ð耀€é€€°â€€à•€€õ€€Àô€€ð退 õ€€Ðô€€€ †€€° û€€à 퀀 -€€À -ˆ€€ð -€€   !%   & " !%                                                                                                                                                                                                                                                       ¾/ÿÿ|îÿÿ0ˆ€€`ø€€ë€€Àó€€ð뀀 ø€€Ð’€€€‚€€°‰€€àõ€€ó€€À€€ð÷€€ ý€€Ð耀€é€€°â€€à•€€õ€€Àô€€ð退 õ€€Ðô€€€ †€€° û€€à 퀀 -€€À -ˆ€€ð -€€   !%   & " !%                                                                                                                                                                                                                                                           Ï/ÿÿ|î’ÿÿ0‡€€`ø€€ë€€Àõ€€ðꀀ ø€€Ð“€€€„€€°€€àû€€ð€€À‹€€ðô€€ þ€€Ðð€€€ç€€°à€€à˜€€õ€€Àò€€ð ó€€Ðó€€€ “€€° à ð€€ -€€À -€€ð -Š€€    " "&   !$                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Lÿÿ|Ž“ÿÿ0Ê€€`Ò€€×€€À€€€ð®€€ ”€€ÐË€€€â€€°ë€€àœ€€î€€Àó€€ð¦€€ Ä€€Ðº€€€™€€°ú€€à-  +(='($6$'=)5 &) -%0)% )!&!$)4# +""(%#($)$*+()4(* )'"%/>(36 +!$&)),,6-$2/4#,(.!"//!84),*&$-'#&"##&2%&"-*&+%%(#,0))1, ,*$6+**+ &,+*+!&!(+!%  %*)%-+(.1%!%+#) "+.'-#)++$''#,#!+#)&!" $$'!.) $%($) ,+%(?()*#  %$'/*'".'+)%=$(+*-4&%#+(1+&"()&. )11'!7*-á Í;ѧ©™‡Õdýf~ùœƒR•>¿`ýpá­ͬãÑuvñ¬õ«¿6ߦݧ—ˆ‰¥F_…ù°«±³“ñ{¥|åC¥A™›ÙY¯Y×3Ÿ3m»4Ÿ®É‹éR±RÕÝ.Á1—jïiéE¥Z‡‡¥¦ó¥Ó —8ÓO½q¥r•9ª·ª¥›Ù›ùW«œÝœŸ¨˨ÛS’å“ݱ±±±…×õ/‡®½Od»dç±—²×8㟣­Šó‰ý—‰u­s™:£;Ÿ†û±ŽÑ°ÁãQÝ^ï§ë9¡D™}£né,Ý¢Ó˜Ÿ¯3½S¡s±™¯R›u›i—*ãk›3³H»ªË9íY­ß9ɪ×yùnÃi³"Ó¦óOѯ¦µ„Ý ÿ‘£[ã}ã~¿–‡·PÅ:Õ¨ŸtÏjÝR…”±ƒ,ÿO ¿¦ó…ùzõÇ(ñJ“£©8·Xƒ›"Õ›½y£V§ƒ˜•ïQ«.‰¹±Ÿ¦±8ÝUÏ¿TlÁ¦å,ñk3ý « ¯,ím£wé°çf¹"ÝÇ•‰çC™cç‚‘G£É®ùw‹b¿ ‹¯‘ë“ÓRÛ0Íi‡“¢õ_…ƒý²×ví?“ª¿ ÝX›{åi›%£ ¡íŸãûOëC¯•DÁcí„ËMá‘Ͳù›¤£Ñ'©'tµt­TTó2É2󃻃aÕ`‡_×U׬Çu»9Ý7¯˜á_Ùté<͉±eŸNÅ -»~…ýyÿ »"‹‘£YÉgË$Ár‰™f²•³«Z÷ƒJÏ+¹²ß ÍqÕ;ÍŸ<Ÿ–ÕQï‡ß2Ëc½ -í‰ÿ4³Ÿ‘Jõ¦ÙpóeÙ4Ý-å@ƒ©Ïfõ,¯AÏ[ÝN©Ç{ÇÉ;¡zë:ï`¹pù(©z•L±»±«ã§Ý±BÍ~§Jµ\ñM‘\«¹»†é¦ã­‰Ãt×}ÝEÓ_Õ?8…¤ƒ%­Œ½€ó„™Øýjñ=‘ŠïqçI猓™|‹DA¿žÍ ý~÷2rc™¿'ßõlXÏXë!‡ë¦¡6…7µXÙïDõD†¥‘ÿáKGÁÏ^ÙH󇵈¥¨¿r‡`™N«MÍÅ$·Å.ý0·~ µTϛ뚳$ñݳ鲓zÙ>÷—Õ,õ+™7¿m§­\¯±¿xCû¡uÍtñeÁ‡Í‚Ó¹¥!™³ƒ¯•j¹iûGÿ$ûruó­q—[ßZ’íží)Õ*ÅLßB×aÿ`­ûFÝ›½T—U—5ßl™‹çFåK½)§ïIÇa£b­šÑ ‹&÷@ß>áv±²•5§«‘ŒÏ|±Ÿ·.é-ÃOãt«%©5‡6¥¹£«‡‘†ûcÍA×Û\»]…ÁH·®™=Ë<ÿFÁ$,½mál‰xÕ®­-ݦû¥·›¯ýŠxÍwçUÝåŸ5¡7™„ý§Õ&ÏIñK›ƒ¯ù”Ó&»>b¥¹ŽáŽÇkÙIÛŠõtßu½Uë­(ëi¹j»2ïR§.£u·tó«Á…ƒD­C£Ó¨á±µ/Ó.÷PÁ¡ -ùL¡Lãm­Ž¥:á{«|§çß®ól¹l£5%ų¨¥©×p…;¡H뱬͙‰“…‰†¨û‘€¡ù0L¡B«ƒå‚£Žõ•U{ã°ó‡™I»v—©1Ý0‡hÝtÍ/·é õ²±bϯ•hÝhµ1¡'—¨ó¨óˆõ åÓCïBÿ ‘±å”}Å}‡0× ßA÷[Ï\ã“ï¿*ýk¥kåuç²ß•¡*Á)ã4“kß5é·ý‹«¨Õ’ÓY•Wãx¿lùJŸMã+Ï -ég×eýD­,£ª÷;Û<áÏ'Åšµ½Á9µ_…2§4ÕUõwŸÅ1Ã0¹ƒ¤‡?Ó,Ë*·¦½[‰€›³Žý®õ‘ç»Gûu‰5ë5½“¬Ï)·—³œ±dX»'µ4»3‘ƒû£Ùû©™÷_á‰ÕJ­K›(Ùǃß‚Ý ë”ׄ©CÃ?½ß°—Y­XÍbå™ù*lñlvŸUß%ça™a»‚±Iç7ßýí¨Ó^ý­¥@ýs×R³±Í>Á?›wá°Ñ5› ·Ûš•dçñ6‘:ÑF«"…%ß~éB¹C›?Ï?ÿI›¢£ƒ¤Õ£ë—ˬ™­ñ­Ÿ«ý™+Å*­)é)•¥ÃDíHÇH¥HÑ=õ›ל¥—Ï—õd‘;áA£A­Bóx¥‹­ãëOõ’µ’é–—ÕpC×CãA­Aådû€§€Ñ§«¡±€§^‹:ß:;—A‡r¹?§CíB‰=Ã=÷]ƒ¬Át™uÙ’§,Ã+÷5—mû3Å7×*Ã¥ÙVƒV©NͧFÃE¿b“„×›œë¨¡®ÁÓ6ãoÍ:ë8¥±Á‘¿˜…v¯©%»‹‹rõUµ ÕIùŸ£#ùk›‰:‘¹Ý8ñ;ñ»gÍ -­m©›¿/› ¿„ƒ¹mÏR—l|³™ý‰÷"¯‰TŸŒ¿tÿbÛ^ËvÕ í›‰v¡‡¡#¥)©n‘©¨Ùxç3Á Ç„Ó¦óGítÑ‚á¡¿Ÿa)³±ñ ç#­žõÛM‹.ûyó•“û÷+‘C³xÛsûl™Y銷%¹…AÏ@ë·|£ ãy•AãO»\ËžÅCýu»¯¥ “yÉ"›F» ³6½˜Å鯡Ž°‹Û›Ù••añ“—‡>PÏç¯å4×g‡ -ñ4·T½wù -ÿ\…)›™§‚£3£m•¦Utïh•°·On é”û;—…Ï¥³‘_¡=»€ÝJË>V¨Í[ÿ3,Çg»1÷R¯uÛeìã ÿ*Í,ƒ Çi‹ã0“A‹¹sÙl›œéË…ï’Ë&½]Ýaý%Á#DZÏ&ǯcýFëÇ\ùš¹•õ5›ïTtÇU‰i÷ß}Ñžçl˜¥„É:‹zã¹4ÿUÉžÕ¯³³dßd­pm»)Û.ëIñ¥Jß?ÏËq÷©‘(뛩sÙ…é6‘—†Í_Ûu»YÁ íAûzùÿ¯Eé¹—ßµ;ãŽám‹Eà ¹ž© ç÷d±T›‡Á|ÏuRÝQ›\×’‰ ;±9Ǧ‘y÷°…|ùoÇo͇©Å4ç ©?•e«oÇó°ïXã‹Ó“õu£fÍßDŸ1«A«Å–ÝÙ21φ…‘í$Ñ¡½``勫骯‰zUrûpÝP½©í­‡ˆ“­Õ­é‚‡¯½°«+ÏL§LÁmí^«€—åÓ­Í?¥dë­Ë‡ W™{£³ÕyÓ«ÍT‹—{íZ‡{Ño¿P£¡h×K·sµžëžÕ$¹:iÙ/ë © -9•c³šõnÍvýT«jóóŒ“ÑO…Q³0ûn»|íl“máwËXóX›zÏ‘›oÓ¦é*½zïy‹X>?陜ó›óbåZã^Ñ{Å=Ù1ÏOý ³Y³aµ›£‘ïÿñ@Û¡JífÛ‰ù.—Q—PÁCç¨ÉrÏ!‰ÏF‰gõœé~ÅG™i¹‡ï ŧŸšùG»;T™3«}ùž …9‡xá¯ßL§A÷|Ó\Ó±ûxñ!‡œ¿£¯»UµZË€ãõV©•™s¥—˜ƒ+Û¥çJ‰f×.ÇS£ÿ’³[ÿ“|ÃË/½F¿9í¹ÿE½{ï5‹WÓ]×=Ý‹Rƒáí•ÉÍç5qíOµͳ©:½¹G…H™~·V»w›p£P—Íé’û ½0Ó–ƒ—ãXù“÷?×½‰Dƒc6‹ŒÅnÃQ~ÿ‡…rïeƒH¿;½&àd©—‹0²Dý#ÃzÏ­¯Né„Ù"Í2Ù]…¥µ‚ãå©ýX‹—•[‡ųóP…d‹pã$Á á7ófÕ¥Ç>µvÕ9Á†óZ‡¬³Ší»8ëã`¹>É›£'[§c›C³<› ߇<…»RÛ™«—i©žçcïï3ïšç‚׊—­±É+Ç<é Ÿ ©=ͱHÙ‘ß|ƒ«­Oãš• -g¡‰ýŽeÇ Õ.ù!ß”ùñn姢X{Ã*ÕGñ˜«cÍCñŽãs‡§‘jã‡B‹eó,‡Œ׫¯`ý†ã«ýNÍ+å|Z½ZÉŸã™ëªŸ\ÍË‘ß@ßùRÝß'Ù~· ÉYŒ¹(ùb¿²‘—6ÿÃ[;£—£‰*u묷(£»X±£¡)±­’מýi‘u¥Yëuí!ÕX§­Vû—|Û-«*µyµ³ÛK¿]µÉ—$ˆÏ`‹µ˜‰¨¿Eë{“‘ÃjßG˜Ûzé“Ã}Ãd‹Q«0Å‘ÝD× Ÿo­8ËH©œ¡yÁ…¢Ï–Ý9áÝi—3©¤ë/½ íkÁKÅ£lùK㜡|㙩Ù!Ńñ¢¯{Ë0—Kß²§¥%ñ9Á½jéËïsá™ïN‘n»`ÕT߃·Ž££U‘mà -«ݤ™¤ݘ*Ñ£ùh…4ãYŸ¬Ñeãpåªý’Í€Ÿ2å ¡,§nÍný›=ÅN»ý"ɀͱ5» ó••“"¥ÿK½ŽûÛ—¿v›V³‰qÕã9Û™bãa©³§žéz¹›@£+åœý{Ëk¡qùÁY»sƒœÅb£Z—œùYÉ¡§ÍF×MÛNÏ“^•Ïvƒp‡KóŽµó±çy£MŸyáœÃhÓ2#Á•é_…‡áLç±!û%Û‘M¿¯'Ã<Á„Ñ<—g‘3§”ÝVÃ3³—;Ñ™§B­hû2•PŸz¿’±+çµ®ûIõ(Ù¡©låL÷=ëÉ%‰NµMÑ«u÷ -óYÁ>Å”™ -ùXÉ&¯3åvéxÙNùHµ¯§\Ñ>“ ¯²‹?ߌ“9¿•·Bÿ™ÿTÅuÙš ¡.×6¹Y©`¥=—JããŠÁ\ÝA© ƒOÏG¹3å"õgÇ -±§ µ@õ «&ñ“»óQó÷~Õž¯¤ßzí ÅËSõ¯áÕiï1¡Q³uÁlñEÓIë)ƒÁ‘aÉ0­i¯€¯0ƒ£®ÿ¥á?½P£J«¬ÿ󚧟TázÛ+™Ó©óÙªõã]Ç%Û&ë³×ƒ¦¥©kó1ótËýÕh»·k£ßÛƒ…=Ï3Ñ™‰•Á«û^§–«ÁQ£/—b‰˜Ÿ§ï*¯7•!“­4÷ƒÛŸ¹RÅ0—w÷®Ÿ‘ó²—ùÇKí0‘œµ`ãƒóJ§£Såÿ «ˆÃ{Ï2¹‘lÁá(¯©ÇÁ ›Wƒ{Ó•÷\ÉSû>ݧsã–…¯ÁŸ@ã­ç`§tŸRã³”i»x³EŸ'ñ‹—h™x÷N“?éͯÙ©χç õN¡„¯µª¡¨Ãuåhá0ñçŽõ³“S©]‹VŸ÷í‡í{árӪ燧 ×XãªË[³9ÑY¿ Ã4­Yß‹“Å\‡©Åp©i§1ï)ÿHÕ§]Ñ“»§lÁ«ߊ·¹D•g™1³T•ÅÝ¡¿fã.ãW™ ±¥§¥‡©fµFå¬ß·?û`É„í`Ã便Ù8Ó¥“$‘ã8Ëtï•××OË7ío‘=Õ˩㈋y߬é‰ýh³VÝ3¹Q©[—zɱÿ§‰åeýM¥-»©ó#áj•1™ ‰ñ¨«d‘Aé‘Ñt¿Rí5›««@ÕKÙ‹÷O³r³mï×,ýË'‰Eãe߈±lãIÏ,¥ ‰šËxÅB» -½(í£“iŠÓÕÕ8­u·eÿ.$Ù©A÷§$õÅi•l³1'©¡ï‘ã§V‰^Á”“¡‹F› ß‘÷±µxå_•VËïçŸÕƒŒ©j‡t £§݆åc“@‘õ©‰p­jƒ1Ç7ûѤÿ‚‘h¯:F¿|£‹Ÿ—Û¹µ?£aá©û1·‰7AýAÉL³®‡8É—õ¢¢ÿeÕÃJ­˜É³ƒTí¡Ãoƒn¯¢³—ñ|»[h÷hƒ”•r¯õXÁXƒgÍI¯Kó}ç©Ÿ«ŒÿXÇYוñÿt-Ã(…‹¬Ý4“+™*Ó9e• ù±%ß¡ÛÑ.û‹±ëÏDÝ«ó˜£-åw•^ƒ‘‰/³&ñ¥/é&ã‚cÿ–é/‰‘ßÓU·¬‰-‡ÅeãL‹@Ÿpç ÿ_åB½›ÿ9ùrÝj®§6…’©^ͦŸEç«ÍeÏ¡(s YÏœ§/ÃÓk½/Ý–—ÛѦ“UŸu£ˆ7ÿ—‘b•+ù£Û–Ñ/™‘·nÏž‘¯¯‡ŽÓz×Ù^ë‘¥5¹,±|ÇZéuÝ”³-çN¹‹>÷rŸg±œ»Kµ«§µgùÝ°÷£TʼnÇ8ÿ…ñjó Ï ‡«,ÏNס݋¿Fõ^ñ>·QÑŒƒ†ñˆ‡4ãT‰—™Vǧë„÷8µ+ŸvéV‡!”·ŸÝ2•i­#Çh£™ù`½n鞇±L©;çE¥_Ù‡7±ïYͪ§[ÉQŸZ…Ù•’‘2Ëh‘™Ÿ=ùˆ… ÑV­§ÃFí"µO­×IÅ@Á_Ù{©­á\¥yéD›«åtç@ÃŒ6¿nåÉk½ ÷“…§åPí®õõ8ÍŸõK‰l³ªõÿl÷3‡‹oÏ·Š§ŽíŸŸÿš¹-Á÷'åÁ‚¹åyÁ³™ž…C«Á}å“‹Zµ:ãd÷ ÷Šç„Ó‰V— ñO™±ÕwíçZ—¬—Œ£ŠÛO³é ÝSÇžýBëó8ÏõË`ë]ÿ"yÓWáÁuí*ÉMÝG§£ÑX‰{¹w‹ŠÙ°›TÛž»…Ç@³‘ù/g¹€Ý)½7ÃWÃ¥ -ƒL‡¢£ ß å:ÁŒ×½û\Á©ãÛ¨÷LÛkÀǧpÇ*÷£Ïƒrû*é{÷ÏV£å—fÇX£©Í×YÅ ³­­×]›}±p™ª½•¹ÓLѯÇ®»‘éJÓA‡ž§xÿ]·m›í§)ÿ(ó ‹‚÷c1…WÛ1é £kÁvåx‹’…ž}á=ã™Ý£å‰¥i¥û¤á ¡‹Ó?»½=Uù¥ç†©Y… ‘|óHñ*Õ-ãP»„ÁŽ‹2ßj•§Y•¤(éƒÁMÇ©±rÉfûœ…O«…Ç_ó’ÇBáxëLÁçH˯ù=ƒ«hû’×c“VçÉCùs«kß#ëp¹/­¨׆£Bá—Õ‹ŸXÅR•~›2åI·­Á4±®ù4ÑŽã1«C½åGÅFÍ““­Ù³£ áéMçßÅAÛ¯ñu·_]ùm­HÙSù3›kÏm‹‹£Åƒ­±…“÷§£€»-‡ Á"­¤õ˜ý\×±]=¯n(ËJÏ=•·xÛVõ3­¡ƒÉT¿ÇÕW§zëoë•åT•wãnýOåé4‹¦™†Ã‰1«m‡ÛŸ7Ý"©”«„ß)©<áH›Ÿåç ã'×H¡ùFù¯­¥'Sß¹Å'Ýe³/«X»>Ŭ‹L™h¢Õ%çÑ_õ!›“±©Wû«Ç"Ç •ˆV»®¯…ÇDŸ2õQÓsÉd¡°ûÝ?ÝwÍÙ­‡ñ+ÿNÏk¯bƒ>³±°ñ<Õz•)·K©Oñz›©÷D¿{­>ãS‘X¯¯£Õ­‘Ïù3Áz㇟#™E¥]ý/›Rë®ééL‹‡û ‰Mé?«ƒ'• §;åEŸ·°· ·œ¨¥xëhë0Ý}£­ë‹Õƒ©ŸªùÝMák³GÓpË}« $»”£ƒuï¬ý û-Ï{…~û—¡iµ§ñŒ±*‘¥–¥¤±§9½ƒ§?¿ -Ų¥PéG© LJÉßtßmã¯ûŽ¥åÇqrÓ”×Ç}§ùŸ$éIá,󦛠‡Z»%ý$/çgù+“œ‘›Õbç-û}žý`Í8½6±n‘¤½:­¥ë.½.ñ íí%½±¢‹G§ˆ‰Ë³iÇ2£cÝbÅ™í«rûq•fí7mlçs…R½‰±‰ׇ ÷X|Ë|§Ç›³å² ¡AÅ©!ÅY÷bÏ«S¯—dzS×å‹÷݈÷}—š§Uÿ5µ‰ŒÝ{Ù@§«Œ§I±ù˜ë«ÑAÓ°…$×#¯‰½f§(¹‚…K㙫³j‹j•3¹)óR‰’«7‰c¡Ã‡ÇŽ£pÉ.÷0±Ï¡á+—+Ñ8§oч¦·¥Ã$Ë—4%¡t¹¤õ‰U­:•Å-­†‘>‹ÿñaÓšýˆߢá&+£*Ÿ(É4½HóÛ«É)<¿ ¹©—:Ÿ%—'«ŠßHé‘Û=~ã ƒ £ÕM›cùfù±XÙ—¡—ó -ݵ0É1ë ³ZáFGó$Á:ÿ¨­©O½tÝ@ÿ@ƒWïnˆ»ˆ¥cõ§É3¯5Á}·<Ë¢ù¢Ñ®ñ€Å€¥CñžÿŸ±“—„¥ýç¢×2ésÁq¯^㻉•‡ócÑE·ŒåŒ¡ï|ó6•7ç¯&§“…“±·3Á[‡:Ù,ïÑ«…tÝ’—™ƒñ¥ëP«­é7ËõPß¿#•#ï›×ÛͱÍ*¿B•±G¡€žû{Sï:ƒí]û=í‹^ñX‘8›r©7­W¥Eß„Ùr¹<…+áM£4ûY¯ ‘Rãh…0ã#Ë­‘Ó;å •-¯¥Ý%£Ÿ‘‹ßÍXLç»–Íz¡›§Å,šÑ¥ç+ÍÅ ‹-Ï ³AÓq‹|Ù:ß_±Oů·H§°£…`ã᥷&“x‡± -ËCç0Çë#‹t¥«ß™çáTõž¥}½_Õ=Ë°Ý ÿS§qášáËñ0¡mÕ5“šñv¿Ëa<ýY³y¡‡¦¯<­ÏCŸA•4Ã'³‰¡X‘‡ÅfÉ'“wçÑ’Ç›£µj_¥V×…«>£%¥¡ïzç=‰ƒµ¬“®ÕŽ¥¬•_õ.§ƒ¢©É°ÿ)›<ƒ=åFÑ;õqKí­°÷‹© ¥ «‰ÑB©-Í(á#¹†ß ÷G½­Gñ‚Óƒ½A‹"¡]ç÷בã,£¢¿¤…ŒÁ­õÙwËu‹3ßõ|ÿ -óÙ®ãÕã"ñH‹K¯׌}«Ÿ§7Ã@㮽²Qý›¥ј«(Ñ‹™‚õC£CõváŒõ‹Ë2Ï‘žµ÷­§²AûAïG»0×t§u½]Û}ãå Á¡…•áaƒ:…<ÙU¥©€·‹ï…Bíh·wÍy¡nÓ"»“£”ƒ³ÑùSÃë¡¥Õ£÷˜Ã~«‰²ÿoÑp©š‰}µ|ÙéUÃRµ‹dÓdû ÿxxÑKŸå ð»éc½!±Í)ýŸë¡ç­±fáeßï˜Ù™ÉÕZ©Zåg±#÷&ZËE•F·ó^Ã_·˜£Ãߎ‡y½x‰ƒë>Ù?ç>‰áÝc"ÿï4×w“‡ Û¦¹+nÍm›Pç[ówíÁ‹¿©Ù!§Z¿\û„ß…¥šýb@³?§†Ï7‘•û•¡¥•³Lë¿‘ç}瞇©‰oñÓN·Lí}Á.¹9­ª•²ûû¢±£_›]‰W§w㡉¡¿ƒkÉ~¯õL¿+¤ƒ¥õÙ­ˈé‡Ϧ³+£{¿z±3¯kÉ‚Áß×FÕ]Õ÷á6áûV¿›œÑ*×»Tån¯o©|ÅžÝ,B×E‡R™0…[õZ¹2Å—žû‡]Ý]¹XõoÙeßc‰"Á!Í‘³M½L¯9¯†Ï…—>Íû~Ù•RûRÅ6™W»6§™£¯ÕŠ“õß×"ÛCù6Ñ!Í“ɘí«ù ƒ ¯!•‹$õ¥ã¦Á¥ëmŸ‰Ës—t£^‹~—#ÇQË”©ƒ›[íQ¹Wßyÿn±2‘0ù뫃MÇÛ(DZ[µfÉ…Z‘-¡Vé\«ÿ£§M‘’©ŽÓ‹x½r¹I¿8©()뉙ŸJû7ƒŽÕÁƒeÙƒ‰0¿‹¿±ƒ)ó%±©Å£³FÅ~³z…LËRt׃ë=‰PÇ‚»L»qïÙ\Á=Ë©x­?ý“,­7· ÁpÓŠõ—“N›¨…Á¢‰–ÿW“{‹í.‡³–ï“ ç{Õˆ‡&¿:ï‰ó¯ÏÅáPÁsùaë?¿¡f™‰á“éq£WÃ8Õ>…„“§¥œ§+“–§§ƒ|Í%¯Gÿ<É«»fç^™<Ý`­ ¥eÛ#¿$¿YÅÏE×-££ÕFÝ á§ç6ƒZ·yéïE‹lÅUç—ýÍlÙuåYñ¯f—r‘ª›yïCÉ ™-¯©3çS…!±'“՗烇FéÓ*¯§Åœ½£‰(¹ˆã©åû‰¯ ã@ùuý>÷HÙ¥,¥Ló¬éŒ‹k¡a• Å•éP‘pï–™Z¥žù-¥ñ%Ë4·£ƒ…TÛH»û'ñ‡w×V±×GÛ ½XîµÏ$‡EÑ$wßF“Ÿõ°£O¡C£yÏ°…—û4»^ánËI¡2«‰“&ƒ®›x©>õE÷Y© ãž™"ï9—\Ÿ»Œ­­²¹xõ±¡¯“—]·•“£—épÁ¨Ï—Ï8—‘—®‘…¬¿¥³å•/ï»b¿ù>³_—±ã -Ù Ÿ?Ç0áWpµQ÷F±>‹!Ó³…?Év¡™½á~–‘qË‹ƒ„B|¡Á(á@…›f‘fíIÉh§¤­ŸÙk§kùVõ4囓v«U¡Õ„ÅTñ‡s•BÁ盽1•x•'ã!Ûl‘Ž­+‹ž×S¿(Ýx—‘…Õ©†‹ª4ékñM—³5»‡ÁRÛŽÛX=‡”Ûb…¥`ɇÃk›^ïù}í,ûQ½ó`‰ÁÕY«ÁJ»•Û¤ÇÑk… -߇f‰>ס µk©£ƒ<áõ>¿&ñ.Ç)¥€³ˆ¹;Ù3í”…(ýCÅ"õ@¹$…n,[Ã:“›ÕcŸCÛ†ó­ñoë±ÿ«¡ª³í;õ6ó:Û?צŒ¯=‹ —u…\¿H-áÑyŸ*¥nå·o¡­µ-ÿ&ÛÙ¥у“žÙŒÉ Ó«õ‰ï²Ùžûª.ÇŸ•õ›;ù¦­^㘃C­L‹¥ͤ¿@õ@Ý'ÁÓýá!¯¿¢§‘Ïh‰ËátÓ‚Å‘­ -Óg«©ƒÑŸ»…€Õ/Ík—…Íj‰Ž§Ã%½šë§í4¡R«iQ‰L½‘³ŸQ¡†ÛªÍœÙKó(±šå­¡@㌯QÁÑq‡ÁjõBᛑÍOý–õxï Û]Çxƒ.•$ßh›t™“ƒ\Ý:é5½‘Ç/µÿ¤ËÏo‰Š‘QÉõF¡I‰™ÁÕeïV«pë$Ñ›.¡Z«•¥U™R¥³ -³v«®™®ÃMéµ~¡\©å¤Ï"ƒ4å>å°Ùyå[µ ýH»?ág‰;³`÷ŽË¥‹Ï6ádß&Á¯§GõH…ñ(ƒ……—ËO«/ïoã„¿…•:Ñ×?ƒ?ýd·†ãU¯VÙ;Çsã’­–Õ¡¡%Ç…_Û_©˜ߣãMó~“~éH¡ߘ¯;“<¡'£}­N‡O³nÁ‰#…UÏ1µh×ráë…Ɇ×¢·µ<Ÿ:é½ÿÉ`ùg³¡ýJ‹”›>‚÷.󧕮ٛq»³¿VÏŠQŸ}‰ï ÉŒé¨DÅx…ÁTóq­bÓXÛ•·Gë‡Ë„Á¤ÕtùpÉ>ÕHãz·÷Vɤ«žÉ’×^£@ÛB£?ñx«D¹6ÃI¿……a³±‚áJÍp‹§£ ÿ­ËmÕRçTµ*¥l“%Ǭé -£ÿJÕ«`­Å çmýšÍ–%Ÿ_¯Í.ñ›Ÿ§·+ÙX¹g‹gÑÓh…SŸ±٠Þ!­§`ñ†›aïWëTå Ñm­¬©å^áY·>ƒxÙ}¨‹ ùq¯œ›5óžzÍ1ù„ƒ’S冧Œˉ™rÝšíD•‘­oÉOÝË?©dÿ1¡ Í›çý•ÁFõ"ÝBÍ°©D£š­ÃY”Éwã%¿†ýƒÏcÁEé§É×Í#ÉNÅÇ¡ïb‘³tßs»PÑNÍ=•ß PÉ\£9שÙAûNƒfå*¥KÍ@ÃÓ‘ -‰›ý?×±“rÃfÉ,›ŽÃV™ŠÿŠÏt¯ÝŽÑ]‰JáRÿQ±uÓiM·Ó§{ûs³Ó:¹\±É‹‹ç!Á®¿c¥.ã5ë37Ó7ï8õ:Ëd•b“™ årá ›6ÿ6ïK…‰“KË •YõTý -µ¥í|³€nËõŒ“’^÷a¹¡ÅŸÅ+›j‡}÷1¥$“#“-ç~¥­®Å¡±³}——õ­ת‰—¡vïv“e—¿=Í4‘VéWñ“‰<·}•vß\­=õ;‰QÓQ™«?—”¿ë ù¡­¦‰§…ÃX›¥å6Õ¡‘<•05É£,»jÉœ¡£ß±­/ûd•pãáUÛIÛE‡p‘zË -˲õc‡c•8Ã7Õ(å¢ñÓH­D­`å±ï™˘ÍÙZ»$Ïi×k¯š¿ZË;É<ã;‡lÇ µ%‡'Û$û)ízÛU³4µ3™Hß©—7ñ§©Xû©M±‘˱Å>ïS™¡¿ˆÿ'ßó>Û3•ý›†›hƒŸ0µœñ å\Õš§hÅ&ù<½†û¡1Ë@—&Á6É ã÷…û:ÁbÑ•™×;Å•¡9Í5¿hÉ çJó¢‰,™jé#«{Ë®™ï­©‰ÍDa=Ýy“C—2©‹vÑ ·‡á¦á ->›dÙ§ýQ‹S•±‡.Õv¥Çwí¹ ­!Ír…à ¿‰» ßNµ ûWÃ6ÿ «¢· -ÿ,¿AÉ á„õ{Ù -ÇTãù—“)—TËlÝp¡0·‰…zå+á:饟b— ¥?¹°½'¯ˆ±xÑ…ƒš›—Ë~Ó¯“B¯aÛ ÝIß»m¢«]ÿa©,Ǣͽ‘@•HƒK©P…ªÉs‡/·‚›£ó‹4Á8…y™ ÍŠé›Ñ–¯›’‹qû#ËUŽ»7©…“6§¡µ–¡-ÏïJñ„ß飧¹vÇc‹8f³…š›‡Pï0‘}«ÿi¡>Ÿ&ÝdŸ÷f±-ƒ#ÃçÑW÷›Û•2¡ ™D½|±Š½i½póuÍa!ˣњµl›sߥ‘Í&¹§Ó Å/ébÉpÇI½žÕ…¥"ý°õ%ápÛj­›—ý¡‰‚«‡óCžé…ñ®½9Ù¬á†Í§­é+Ýu·‘¯«Õ †©4óSƒ!ùT‘%RÇœé—áo÷Œá1çxßn‡¹Ný¡¢§<Åw¥Ãx©íQå#÷ˆ*í[óUŸ)ŸF÷l¥­“ ã‰Û7—Ÿ¿Ž—í¥—…G‹=¯ “jé!·W¡pÝYסû‡ó3ÍgŸ4ñf¯‘6ëÛ9ÙŠíRã³UŦŸKíÑÃañIÁ5ÿÉ_ÇPÅ‹½a¡ãKù÷•» W–‹’«)¢± ™—¥{Å…áV±qã•£Dû$Ña‘ ×$•‰“ˆƒ&ÁI‰“áÛ”‡‚½¤ÓF¹Ek;Ó$×\çDý˜·q)Í'ÿ ãF“Ý_Ã,ÛÝ\©J…i™¥…ÇMÝ û.¿y±—ý(¥G§Éý@÷”E‡;Ó ‘g“2‰‹nÓPÝ™Z÷ ×{¡“F÷*ÛiÙ+§%½‡×(c‡!ÓŸï ëK—ŠÇ`¡«Ë=ý&ã<뢙°ù¹|DZ^Ãÿ¬•×ûhÛ¬Õ@©v³;‹­çš¹T‰jƒ‰Ý‘`…l§'Քũ¿C¯*ñ£¡¡~± Õª=Õ4ùûgû/¯¡ù\íuÓû¬Í—‰Hë^åŠëj½~¹—§÷Ÿý5÷y›Só‹Ÿ€¡”ß™P›šÅM©©ÿŒÇ'‡¥[ךÑ›…‡j·d‡3™Û{³W—¯ÓJeÕNçWÑÑ7¡ ‹°á«³Bý7áfç÷™§ õ*ý_™`!ÍQç’õ-/ñ—¿­³Û Ÿ«9Ým© »Cå ‹ÿuÇŒ•Ÿ™%åŸûa±S‹uéšÍ£‰2éhÿ¢ï+³Qó ßœ“IÝá9×ÝoÉ(÷¬‘‘År¿M©~ß £¨‡5‹h·õóBãZ× -Ï*—vá®ûe‹%ç -׉‡^¯™•{ÝvóƒSƒ™ÉmÓy¡ŸÙ‚¹a…©«³›…Ó3Uxó.“ ›Ä„¡S§>Ë÷¯év¡E‹c¯@§S­}‰„Ñ3ÙûÕ+ƒ/Ç!чÇ¥­aç_‘DkÕx‰¤½¯»!ÿ7Û¡¿X÷ù‡¹=¥“Ýn©¯4±…­Í9ëq©hYƒ5É¥†ßKålÛ©Ñzû‹aêëÙωtƒ`³³yï÷kÃw— ¯#½§Ï ÃN¹{“ -‰¥ÿL×_—a¿¡ÃË«sÍõS¯Ÿ‘$©¥›d‹ ‘¬…qÛ8ñ¿œߪ‹9¹]ã6k£o‘–÷•”ù‰¡Šõ Á@ﯫ°ƒ•£KÍVûHÉ=ÁGáh¡±‡Ū³ƒ™Ûñp½œ—û -“Hù~›¯»µ•Ÿã&±où9£rÇr{Q£GëF×jÇ‹ËíGÍGÁgÓ‡­Q½eßeó‹Û%¯?ç¡“ Å“á[ƒÛ²¥²våkíJÃí–Ór·aÃbÿdá’ÕOýÓ›Œ“€å?Ù'­'åçeŸ{݉@ÅJ£•Á“O±Zé@ù?µù^³•½ ×DùDÕËŒ¯H‘H‹ŽÕñÕËb‘£µ£©ß1ï•#«Eë%½%去l³h«TÑTÿ£™Ÿíù7éXϹbõb…œÁ§ùeµ§£›››¦ã-‹få•T³^É»z§WïŸ.çnç/µ,ó‘ƒsÏŽá'û‹×s­@é;ƒ}µµLë|™“*µnÓ8¿³‡·€Ã2áqÙ“»5ßv×–§&¿µK°‡„Á˜­™áË(©¥‰ÿ‰÷iϘùN¹ Õ•žƒ‡°£¯ÿzÉ?«bÛ ³!¹³õOŸ>‰ïå•ÑjƒjÏ«ý¤«÷Kétó0“0Ý#‰”Õ'Á££¤ûƒ‘~éS¯’±”Ùß/ëV¡˜•˜…¨ƒUõ&ó;Ù<Ù[‰‹ϳ½BõAßP—ª¡e­&Ó%õŸ½G\¿Ÿ²ÉPëñ×ïPíiýœë1¿2·h¥Ɉ‰á}Ï}«•É”“íŠáOÏ Ã …¦ËVÿ}õñ…-•n¥ýÙ–­g﨓¨µé¢Å°Ç“ã7›²±}½ ­¹‹Ç^ÿpÉ/·0“ëUÑÕ÷Õ¥q±z¡³ßI뎩¯¡;û+ñ‘Û“ƒ^Ï/íÑd&Å5ƒƒíx¹„©°‰?ëBÍLűÓBóªÍ©¡ˆ;—p½ë·š¯yÏó7½8¿k¥8Ój‰&×)¿§™ß+…p™o§‡¿­{‰|å.‰ -½™›U¥SÑ Ë\¯B×AÍ £²¿Ë]…^Ř©í‚¹0ë2ë"«'Ã>¿)¹*¡¦¥g íaù_Å‚Ó•‡€ë€Å`»=‹s™5Ç4ï'­£iýªŸ°³×@ÓE÷ñ•Ëjý,‰n±m…5Ã)á/Á Ýß›ƒdýózßxÏB¹ -§ ýÝ€¹ÓÕ¤±`ñ_åS§ÝTÉlé]½«ãR·:½¨Ñ­·‹¡ù²ïAÙBçKû±ý§}Û|—ZÁˆ¥1…¡Ûÿ{¡[§½‘ Å„±Õ{³|ƒF§ -¥˜û˜‰~³„·2¥ ƒžñ}Å|»ž“D…>ËTón»o˦»Wï„•œÛ’ÏŸ§*µ…j4ç4…Ý<“ƒªÝ;ó=U‘¢ái•%•*ÿÉ@ͧjÑié0‘½…Û„ËKÿ˜É!­cÓb“™ýMƒ7‰XÓeÿ©×Õ±…–‡u‡1­y¯Ùµ™“ù®‰¯óoù åz¥§?· ýa‰eÙ9­­÷^‰Õœ¹8«¦çˆ™GËAë[ß!Íc±QóN…N½Vù¬Ý=³5ß49›ëz‹m™kµ8ÁŠ•ÑDã*ý4Á^å‡Ñ -…x‘ ¡}ÁdÕÕŸ_á.ƒ§ÿ ¿ í¬¥’ÛWÓ4Ûy×:…]“•‘Iõ Éy¥~— £7Ÿãr¿íÍdá£Ó«q•tÁíyß;¥£í¤å2…®…†¹FÅ©‡µ—åN‘‰õy¹·=äùás‘{»Á3¹ÅŠµbåDí™Éz±i¹.É¥¥3‰_¯|ÿD_ñ-ñ‰åÓ™‘ç(„É ‘—×®‰)··p³ Áa«8­…Vÿ%Ã/ÙoµAç'­R×Õ“ÿŸ×”ס:÷ZÃGá…«6Ó ÷ÉG™pÅPÛ…Ý*ç®÷n§T½ ÿ;ó"¯W᱆ýÛŒ¡¬Ó+Ç,ïf÷–¯…‚¡3ß6ç]Ý1§|ÇeË«¿‚÷ ¯m‘?ÑM›nŸ‡Ûfí§…E½Ù=ɉßr‹Uï2™(Ý•§bO«³1ÍJË–ù­×BÁ²Ÿƒ¥>Û)鋃¨Ï½ŠÕ±NÙFÏŒñm£zª—,ý“µÛ°·„±a§§r¡©‡Ǥé£×mùlùÑ‘¿”Í“ýã‘á‡íN—N¡²:‡ëX ý3ƒ‡C…:·5Ó†»«á4û £Q·ñ«4“d¯OÇ瘿…1‰ùiÉj•Q×uƒ‰¬hí'÷W¯Š¹ûvñ¦ƒaㇿ}ËNûÚ£ן·…ëŠõp›±‡d5ƒvñˆ¥ —§ -Í}©S¥0±¥×0¯r…3ómïMõ#ñµ²Á%½¡ß“ý³2ãB¹q³ õ†߯›•ñF«G#™¦ÿªßbÙ±³ñ:Ÿhó‚áX×/Ÿ+§—ý^“L±EƒŠÙ‡†‡@­„÷»a»Nµqá“‚…í8 ñc³£íq¥ïr/•›‹(ŸO‡[¡ ç£á—ïtLídÏ•÷I‰.µ'«¯›Xóp‡Géó¡P±•Ûñ¯¯•uÓV·{ï Õ!Óv³ á‹ÏɲÏYû«-ážë˜Ç;Ë{•XÁ—Ûa×£ŸiÏ“íXÙ#½o¯z…±Áwµ=óÃB•`ÙÙ “R­_ñ’Ío¡‡…“;›èÁ —–ŸÑ%ËBÍ®£–‘výÁš§œÝ„ÙˆÑ"ãHóÇ|™\ÁO‰Aµç"©õ`‘ý¢Ífƒ­ß¹U….•s™!Å9÷ã{Ã&¿-¿gÕ©•<ÑHÉ#ëd¥…÷Jûb·çOý2‡ÿ¯ƒáñgÕEÓŒ£sÉ|Å ± ¯©TË,«˜éw¥R…wBÍ7ÅÝŠ…««=—©Ù±ŸBóDzÙ(÷‰±F•k¹5ñRÃß–½Y‘“'‡#Ÿ"‹–Ç–“s³Rûˆí<¿%¹”¥™ûTŸY¹7—ט¿™Û¢Ý(±„Ó…¡dËœ±J›ŠÑŠû©‹©©ŠóŠ±hÉq§ˇ³g¯X¿IÇp™_Á–û¨«Y»V“™ñƒã²ÁxŇaí˜ÍS§!ÉÉŽã€2Çd£±Ñ›÷³k¹O­2ñ,×`ǯÛÃ’›ŸæÝ¥‘Ÿ‡S£R‡ª‘Zå¨éT—õ™å¯Ç—Ÿ`ÛYÑwÏ>¹^“¿u³7ýU¥v‘Óf™nã/ရÑsçwR÷»—¤¿³¿^£Ñ2©¢íƒ³cÙb¹c›9«FӮɕÉ$µG“'Ë …µÏsïU͇YÕ[Çf©rë’¿K¯]Ý·EµŽ¯l6™ëyݯÿ›…{“h1Ûý;£¬«ÃKÁ+ßš“¥•=—`‰žÁ~Õ2Í‘¨Û‹íW—dï Ñå{ó × á™S™Ÿ¡cÙMÛm¿€ÿZ鱕¥°± ¡b‘B£"N…£÷€Õ÷>™¯Ó…h“1i•ŒÇ½ çßUñ¡?éˆÿm¥4É뤻˜á˜—¥éß…u»©û£ÙvÁ¬ïû£‚Ã5“Eƒ~‘Ó)˜û<»_Ï~×¥·N¯>•€ÝH—%ë ‹›í -—!‰³½2µ­€µ>³\“²÷¡ñ~¥Û˜åß»rÝ©õ0Ùiù,Ý6Ë8£…¥”ÓÕ"Ÿ¹S±só‘šÿj™Ž¡lvý¥jÅ(ë–‘°½c¡OÝ!ëk¡8ÑïŒÁ0i—R÷4Õâ§aå~û›µm¯8ݨ¥t•¢‘#ñ]Õ²µ{Ž…}¹}«‚…Ól×[ëïª]³¥½k©߆ÓZ‰'ñ2ïl›4l·M‚±@í²û½ù’é[õªϱƒ±•ÉB×Zï\ÑZɬõ?çR¹Kí ï2Ùû]ï_·`×°·;±‹,©_“aåa¿U›¹hƒiùtß­ÙŸ‹ŸÕ .7µ¡&ÛGµõù:…±‰“%݉ßiÏ]õ\ã?ï§ Á¹‘—.ë-™XÇz‰Iï>³¡±íe§ióŸé$ë‚‚·7‡‹ûχ|§Díù&ƒE³KÑJåo³“>»@ÛL‰…µsÝsµ­·0çA‡z››B»Aµ!ò“=ý=Ýéd‰3¯2÷  ±£œ»Z÷/“/ñSùÁ“í’…‘Oï—AÝL‹¢Ó—Õaï‚õM‡J­ƒå(ý'ƒ@‹ï›mïwÁç±&ç2‘¥ã¢‹ã‡››š‰[ý…ÓM™Mƒ0Ÿ ëtÕr‰ª¹ÁD»F“cŸ…fŸeûEÅ#Ñ­ÿ¿7ý|£|Á{oÑñwu‰sÉa»,Õ<¯CÍB‘‘w«t™FŸD‘€ƒ Ÿé«ª¡rýw«wýo›‰C¥ÏƒQÛ»é0±6WÅ¿‘¹Våb¯T­5å5¡­û ÍûŸGémD™/ó/­|ñ£`û&ï·1ß(«2µ#ß‘ Ó/ÅQù%˃µr“QíbñýZûZÓÛJûË·‡×9Ñfý1ÁV§0éi·¤¡PÙd«e‡²Á±ùy‹ “¹³ß -Éã ¿4‡¡_›AÃL•ŽÝ­¡©–ÉV‹6¯‹÷(™…ïc¿5ç;í=ë_Ã"ƒ°ÍŒ³§‹N«~ç€Eç9×·±Uñ3½¥…©«²áÓÕ:÷9éN¡Ç ƒ²‹š«™Ë!µµ7ù–£Çb÷sÛtÁe߇‹T—X×P±. û?«Jù¨ý‡íj±Œ‹O«PÅOÕ§‰]Ïa›‚JµJåAÁBó_åƒñtÿž¹%Ó×5ûBÝC­ ËÓ§½Ÿßž©#…moß`“`ûU«“n£N‡W«VÛ³ÕlË_`•…á;Ù¤ñ¤í+/ã2Ç3ŸV¹w¿¯µ‹“Œ™¬›—1£0³‚ï!Íhÿg…/ã(@Ç?ód‘©¡w÷wÏnõ•KéKÓû“ÕÛ§˜Ã-©‚¿ãJ™@Ñ&Ÿqµz‹BÏÇv[ù[‘[ë›ÉÑ,ù§¹n͈‡)Õ)Ù”‡ ¹Ù¢³†Ùƒ‘­¯ÍŽ¡“É{Ñ€·]­•Ç~¹f¡gsÍ«ï”ñ/ÍWßY©e‰¢ó9ƒ9·[•}‹wÛwçiÓ‡-É#›$¯.÷e‘­½¬×™±PÕ_×dÓ„õ”¡šß×í±Ñ(·§³ûž±—0×f·g¯tÉR»Bá8É9éYù•çq¹r·R­Ѫñ©ÛxÙm‹ -ùB\Áž‰ ¹…•SûŸý ÝFߧ»k‡kÃÝ/J• å3—c×NáBñ ã:û9£=ƒÅ«‡"åË%õ$—Ÿmψ‹Õ€‡Iͽ<±w¯Uï“Í6Ï;éC‹CáIƒ(·FãE×~Š·UÙTï6Çlp—BáEÛ"3ÅùÇÛ«½sz±yó@—‹÷š¯‡™ˆ+óW©E»EÇA·YŸPíP·A÷¤·²‡³»yÁÅ ùñÿ“í\™ÿÉ7}ÛÃAûC£q«é:‘9“[ËŠŸnßXÇùŽ³'Ÿ½±±›°‰°©uï°¿í~×lçt• Ã1ó·ÿ»(‡—Û,•¯Ù0ÕPÍ`õƒéÙW¯d뜩¦µ†Ë3“×%©ç‹jÓ¢Ÿ‚ó4‘ Ïšd“b³{ýóDÿs·"›HÅHï;åfícé ÿ:“«54Ë¡óÃñ4~Ÿ«ýeÃm¥½»û‚õ–ÏT•ësÉá•Ç§¯³¥(Ñœé|·“ýV—=ÿ!ƒ óË.á¤ë ËW`·³o­.õÉ*‘ië+á³.¿¯sÏQ“¦bá%õa¥;ã[ë*õ -Ù¯½«aÉIÏ(åq›’ýP‘r£(É8©t-ù#Õ7ùõ݃‰aƒ¯p™šƒ -ãf§3±,É[•EÕ0ù—)eÁWãq‹Ë—¹šñ[ç8§Šís…˜ÅV¹1ï{µSßq¿1·uùŒ£Xƒ“¡_½^á<ƒG·Z«šÉU÷“\ýx»*‡›Kÿ¯ŸW¿‡Ÿ¹¥ïƒ—‰ïjÅ8©’ñB©a¿ŒµCÛ Ñ~Ù*Ïlñ‡Ç5ÉJ¯SÓœ½b»¡í6±шÍšçM±:LÉ:¡Ÿ„¹ ãGý©¹¨Ó¤ãlÅd×­ïm£tçL©o³>Ÿ ÓÇ…·4‡nÏ%›~Ñ9Ý -å-ÿ)±Díïpñ'åš3‹ÏŸ•ª³ÓT]³o×&˳D…Å̓õWÿ¡©¯ÿ‘sûÝ™Œ‡q¹P« Íu£ÑR­σ­rŸs›­Ï„­I©ªÕm¡Ó[£Áƒ« ß ƒ›Hí“ó[ÕÓu“‰·£›±7ý¯Ùzù‹ë£¥hÿ>É©yµ”ï@¤Ï9‹Ϫ/‘kÛ£*¯-PÃiׂå‘­ÇRÏJÓ@›`Å÷BÝzݵõ1µ.•±¡³«ÝíÝ[³’ᣒ×Ç$‹`‹˜û!­1ÅWã{›e—›™Y»»›‘]õ•ó‹5ÃsÇ­ùƒãNÓ ¿Sçp™”‹õšÓxц§¦¿‹ë'ëNóç «Q—/‰r¥p“4ÑU9í9?¿aÏHH‹§:ùPÑQ…³(ˆŇ½uŸjÝ“Åù‘²÷M¿,Ù_ËfÙ-.…J¯Iµ(ËnÑlŸ•‡é݃›JÿœåžÇÙ¦·jÁ2Ù)壬KëÑ—ù™ÏpÃe›LïLÑ0ƒË¥ͧÕ°™ƒŠ§m™2é2‹*テõ•q…PÝ“—¡Ç€‹¨ée¯Å˧»¥‘^—~ñhƒå˽Eá¿e±¯Ñ éœ×—·fÃp8íÅ¿£“áŠÿ²û°¯ ù$ÿV£L½vɯËzÙn÷)—IËwñVá^ã=ñYéƒNãC¹¢ûÏÉÍ’ÇO³ŒÉiµ¥å}«[ï(5Ÿ6ņ½M儗ݧ™•÷²—e¹¦¿š†áN›/Í í‘Ƨ~ù]ÙOqÑxÍY•‚“5Ë+ù ±’ùÑ:ÙëX×!ûw·l÷‘ëZ±KÅËeë†(Ÿ™CÍ|±¥é1ÿ±‡‰ÿY­xÿ®ß‹ÕÁŸý]å˜ߨ¡·$±žýEë}飵wó®ˆÓ¬ãcF¹ ¿Wá`Åtã祻J…©Q‡‰—Vû†‘N«3ç—Ñ#§’‡¨ßp—O¯‚™KëaÛ‚û,·IÛ÷`ßaÝ‚§¯£v§•¿ŸëùQù;»uç‰Ù•ZÓ}ñš³b“G¥<‘LÍë\»}m׎é9µ÷uÇ°0›QÏxÅg»¯J‘Sñ^Ç9ÅE±WµcÇVãu•«—_™.« ÍR÷:ëM•?ýSÑ”¥ˆïžÑn»™é•Á§›á$•¡µŒÓ0ûDV‹/ßo‰¦£&ç°»’Ûqùª“ïEÑ\‘,µHýk¡¥*Ûã|姿‘1÷g刡/¿O³%ëHùxënÉoÓ£Ó#É‘ï?­M±/ç$±ª½–çu³ -ïˆ"Ée…¡‚‹ˆ·ËL©+—ïF“íw•ã”¥#÷S×>ýg³#½­ÿG¿ƒï‹µeÓwϲ“Ž‹“˜Ç“å…“7ÿ‹jé3ï%íg±<ƒ׈½£<ÿÇjß"ß.õ€ë«_Kû5ƒÏz¯Zݳ ›éŸ¯ŽëÙ±ù@³JÍÃœñ7¡+‘W7¯_³¬„Óc™z³Ç’9©@Û»e©§Ù%ëÝ>™§µ©÷‚GÙ`¥ƒå®Û›7™Q¯$— -\·”Ý­ŸÏK‹ƒ·¢ç)éa× “n…8·)±¤Õ¥ª»œ­zéQ2åRç“T˽“íp+½#ÍKýÓù8Á`çVׯ­<ÝïZƒ‡ÑÁ°Åq“”$Ó-¥9g×wﮉ­¡… …&ϯ¿ÉtÅj• ÷6ë&ß<›v£jÇ+¯+É¿N¹A§®£°Ç6³$íEñy{˃Ÿ9aåj¡jï¤Í„í¦Ë1á2顯%‰`í_É6í í ›¡ƒé×›€ñC«:¿QÃ㨱­­w±¯›û_Ï_©ÿ™;ë(‹)ï$•I—€©÷—(Û§÷„¹@í@ëGÓDõ<™²áˆó!¿ªËû Ù¨©Hç™».Ñ©õ¨ÙGû¥+‡¡¹®§¬^aá‚Óž¯"íë<ßWë¦ë,…s¥w—CñW‹1£¦ƒ-ÃSÍ¢ùC߉ÅaÇ]Ÿf›)‰¹õiÿƒgyóV‹'»/Í!Å)é¡Ë5Õ£)ë­‰ã ÿ#Ís……ÁNµ¥רÛ>¥ŽÅXÅ’í-Õ ‹œ½5ñ"·6½‹ï#㱫4I—ÛPã—Ñ`‡o™§©yßk¿w…Ží ÃTë ¿¬±vñi“q» ¯”¯~Ç Ï<Íž­q§OŸž…@ëÏ:óï[ᨥb…²ÛvË™):³§Ç“ ùÙqÕ|õs¡k¡’¹¿"ݱ¨›ž­O×x©*£‘ëY7á|£2ç&™™Á€õ‡éjÛ®™4á–ñ²©“P¥‘d£]Å­Ï”µu£xí>ßQÑ»‹ÇFÿkµ‘çX×Wí°­fÛ­—‡·9íªÑ-çBݪÉnýc¿ù{¯£\‰®¯ …óÿy¹ Û2ƒ2ó*á”Ëó&›&ûm¿G׳¿®¯q·*˳Ũç?ÿõrŸrûM©ŸkókÃ#—o©±ù±­lÁ™&ñ&׉ÏU‹J—ëÙ€ÉAˤ¿p·rçû”áó)¿o‰£…³Ñ1Ûˆói‰½@±Aã…™–·Íƒ[µ&‰«Åc÷Ÿ‘ŸÁh›+¿~©‘KÙ²õ)•y™>½R¯–õ7óçëc½»H‘o¯°ïD©RS¯ÿµ±ÅIÑIí1‰mÅl§#Õj.Ç-í¯›:ÿ2å1±£6‰«ý«ýz¥פõ£µ6­0ùÕ#£$Å¢‘E…›±›ËDƒÑ)·C÷$‘ Ï‹ï—ñó”¿3멹`»tå—™„Ï5Ñݲ¥f‰‡©sµ¦ãŸÛc«5åX£HÕ˜Ëië²Ù Ÿw‹}“¯Ë›ù›ÏZÁùAçŸïa©bÅ›µU•oÛDÁ™§…‡Ÿñ°·ž“µ)Á’ñd›Y·-£.™TŸ· Ÿ«†í—›˜¹uõ„“JÇJëƒÛ4³p©qógóaÙ³õ“sé›× ¹#ŸLÁL³)ŸÓ‘Ç×¥B©V©Gǧ@ÛRÿRËÛËpƒqǪ½½¯ë¯áu<—Mí2Ã……çd© çœ­œý¥ÕuŸ“÷’“pÃc¤µ å–ã3•·‡TçPój‡m¯Mÿ8½,ÿ+ËëQ­‘”Ç[ÁªÝZé­‰w‰+¥7—°•¨é˜Ÿœû–ï=ïÉ5³°«;Ÿ›ï -Ñh± -µpµVŸˆ×‹¬‹_Ÿ,Ýr—¦»™‰ ¯h팻¬O»­ -õ~Í¡“.ý¬½4›*ërƒ$Ïq³OóœÕSï&©ó¤ùE‡M¹oÝ÷oñ0ǃYÝlá3›ÏP¿>ÅSƒ«O‰b—‚•ý-Ϭ•]©•mñGãgÃŽ—L¿Š‹¤õRŸ‘xùŠÏMÅéfÑCÝŒ‡ñ“Y³¢ëgpµŠ­…¯©.‰Ÿ¯v·•ÿ­E㬠“M÷‹“3½íV§¥ÍP¹HË"Ÿcç%¯6ýn•ÝmMßC½‡Aý›ãbµï¦ç\éíM¹«Í]—•ó†›–¥Q›§-ù1‰y¥oëS¹œ… ÿ-ýHë7å¹Já ›g݇Íxù ËZÿP«”Ý5ë@£M÷ßMÓaë~±{Ù&å8µ[£žßT£ Á-µƒt¥2½h‹ Ë^ýtï«‘PÅ ™$ËGŸ³Å3¹»—9ÏS­]í(Ûp•§«›±1‡=é«IÏWñ Ó€·!¥¯¹Õo³¦³­±kÍ‹µoõëlÃ!á •.Oó£ŸHïH…ß0ÓSÕ1ÙC¹ñQëRõ­ µ¢ߤ)‹7»ŽÿŽ—s×h½KßJ¿?ÇÍM•,ç–¿—é`ñU«<Å;ƒé©™^ý[Ñ}áDáb‡(ý)ÙŽ± ýq…'ß$çGñ?ÉE©F§fó—"÷,«§É“ýžµšÏ×nõm÷E‡$'—ƒ••§ý‹—SѨ…ˆ¥IბT1Ý‘Ù«›Óã†éc§³¹zá]ÙQ…oyÇGñ5ãDßfë¥ÿfû¡µd‡Q›#õ2¯¬™¨ƒPÇš‘¦Ÿ-ª©9›Eñ…­"Ë:ëbdzåhŸ/­$µ}ÿCÓ »±Í”TÉÇ ñ$å=ívû¯—’í#ÕCÉbÓ•¬Í\™9×'Ç:ÉZ·©û²ãÙPq©p£‰å%H…©0ÿ|…Ÿ³8³w£«íÓ~ý9¯ª™Aû[Ÿ’ýGC›ªÃríý’Ó'k¯wñ±Ó5﵇õ á÷¨Óˆç”µ™?óMåpá‹ ¹¯½>…*É•Í^Ã;­ó—Ù³²ÿAÙa™Ÿ~—?¯ -»²ƒmײÓ!Ë-³‹Õ†åMÓ(énÉxÁ/»D½\Ë•“‰\å¥TÏ0“uû®ËŽÿ~Ñý µYÙLÁf¥Ÿ÷#“ë`·@ï¿«ãvõY -¹L¿§©6§ɧ©$±jósÝ£>µ°½gµ"ƒ¡Õ­Ÿ­ñZý8›D‹‰—«íŸçhÃqÊ—•±(ù¯­k©w‹²‘YµW÷qó“— ÑPµ -Ý«›0ë4·¡‡XÁ›íS½¢¥^«l»ÛëEí‹¥Œ—•|›§µ2«1Ÿû§vÇn«ŽßOÛç ãwûL÷Û/³¤¥ŠÏ‘"ÛnÑhÉ}÷ ý6ÕqÉF«!ëxÙ ‡+ÉÑëDñq¿d»p…6­UÁPBɃÉå9…Z­‹»¨Ï’IÍU‡©®ËFû"ýŒ\ù&»£¡`™‡ß]—^‰d£ -ÙYÏyó½I‹—™ù«?¹!Á;§X©Ió€ûj¹“Ӓ餓(á²Á]Û5Á&ñŸË ›I¯ª½lùvÍ3ã\·J©B£eÉùUõ ÛTÑ å&ÅKõ¤óÛ!åV釯‰6ÙRý뙇£¿Ý|­Fë;‘„çQ³•—óI“uñbùáG‘®ù)§d•£å¥í©±ÝOûP±c׋Û -“lÍ"‘*Ã]·ˆ•Áiƒ˜Ùfõf™m“™¢™[剈ñr•6 ‘'ƒzÉu±¦ÃZ‹€ßEà ‘ˆ‡,™w¥Û³Ù7ýK—yá*ó¬§y÷%Ÿ‹ÿ±•zÅ«‹¡F‘!›ï~ç¤ç©ÓGÛßV‹,ÃÙJ©K‘tÁy›¡M£dÙÕ–‹¡µDœ·b§K«©gÙg“Ót±“‰•‹³3Åh³@­JùIå'ác`¹™§«—Ÿ¡ÃCƒ³P£hÃyû8­9Án­3íÿMÇ#ñ1Ûœ©mÁ…™^ÝÑGÃHù€›Zõ'«nÛ6ýÉ–ñŠ§E¹¬±;¯¡NíÁ¥¢™½?-¿¨Œ×‡–Á'ÿ”Õ™¥aÃU™‡ƒ­ƒ­¢±˜óé}½©)ݬ“ç×<õ]ý}Á‰é«Ý… µ ‹+Å?»Ñ“Š£Iÿ¦ÿ§½N™LÉ倅"¡!­ˆéÉDíœÁœÑb‰F½ªÃ9•ƒÛ~¹Š‹YÁU·é™¡¯§ÛQ«Rõí†ÿcÕA½ˆ»<ÃP‘õ‚Õ‚­6Õ6‰±µ±÷{á‘5ë6­¯¨Õ‰µ‰ÿw¡xëv•\¹eÿ¯xÍEí…·Sý‘§Ÿ‘Å!‰Yó<Å{ÿˆí€Á<·‰ç¬]­ £~‡H‘ý‚ÏbÛ:Ÿ”™••å)Ù5½®³Cñ`Ý$óÕBó\Ñ•‰ ‰¿_åÛd£«§HŠÿ©‹íF‹;…cŸ!ÏѳµB©\å`‘盯µûQÕ3¥zûšÑ¢8±YŸ ïd½‚ƒ*˜¹d÷!éZ›”ëJñç•ùO§g»Šûtͽ$½*ûkÛ€—Á7‡ ©ˆ­SÇ”µa©}Íš« -à ‰‰ÃgëW÷x¹›áy—“Û ‡e§±ÅwŸ™ŸxƒŸ©áCŸ ï±ïŽË ¥mÅŽ™ áŸ‰kÃ^•Åz›®ƒBÛNLj¹’³ãjÝŸŬóñ–µÉK·«“©Û‡÷tŸSñÉ£…°«÷ÛZ‡’Ѳ™‹<ÃáSó ½;Åk­¥W§_õJíÕ‡Ù£™U­—«H©"°í¢©“¹­››‰Z'ÿ•&É™͆£8ÏÁ*©¯(ѧňçkÍ¥»+&‹¯×QÓ|ý£Åoœ§ã³lÝK«gÝg·iëf&Ô©Ó=µóvñ)ýIÙ†½ƒ8›„ëˆϨùdÓ›çÉ -Ý+ûJÓ¡· Ï.£g¹y¯}ùZ>»S³sórå<ÅD—D¡¿óó å­*ÇL‰4 Ï™³IÉ^Õ\Ëy™y­vË‚‘‚ïkN³Xɳ¥± ›!½"Å_§R8÷UåWÁ,µ]¿j²×á᪹Zõû‡šçªˆ¡‘÷-›ç,ƒ›¿¡¿L÷A鬟 Ó1‡ÿ³:ËYývçŠÏ-ÍN¿‡•…å¯e—q‰œ«¤ãi–Ûo—@³f½ÑÃñ ~ß{™ÍZý õ‘.£íC×7±»Ï§¨‡\Û[ý¨éo«z£¥<³…ÕÕfÇy³ÿq÷†¡÷›Ç‘­bÁSù†ù¤é'å -Õ~˪Ù¥6¡^™gß©L»Ÿ±Mù«‹[­~‡V›8÷Q»Aȇ«×JÛAI妇­•"é8µ$éyÑ[õŽ»¤ñL…Š÷7ƒIÙDË ©ù‚©„Ù„Ñû³q¿!E¹®×Ë6çÁZ›Gž•N­ ‡b·¯½Qß-Ϯզ…j½³‡v¥™e‹™6‘&ù…ɦ«^Õ -£†§"ÅÕkѬÝW“}6±gµ fõ=¹'¿·'ÿ†½D—ÉŠµƒ‹çzéÅ­ ßS¯•‡˜Å<õeµR‡%Ùœ—FŽ±½‰£1ó?õh…k©&ƒhå$ã)»Iµ5éFŸç*»Ã\Õg³¡GõˆÓ>íŽï…‹{“oËÃù‘érËšõŠ­£»n…M‹ç“±‹³ý*¹kÅŒ««ãV‰¯\ߧ=…‡2á5ƒ«ãz—<…I±ÿ„ᬭj—xß3‰8åçjŽ«’»cçb‡Ní¯[³e›ˆëŒãé†DÉ‘§‹óF*á>"”Ÿ—Ñ@®·#³¯õ¬ÅÇN‡“u…#×z™Oýÿ=ÿ[ñ™±–—k±VÏ¢©Ñ6ß«¥Mµi§šåQ­‚ñ¡™íU½—× ×ÿ/¥ ‹†ç1®Ç«#Ñ™J§eçv§„… ¡Kë -¹ŸÑ49Õ•ó]ïë‰ï +ÿ0Ñ+—™›‹±=‹HÑvóE‰O¹Bß’f‡gý:ï^Ö™ ­eé§Pzÿ?ÍHÁA"sÉW»‘·–ã_õzíšó©NóA— é®™vínç:éÿ°ÿ¡…É]Ï #£Œó'‰©Õ‘Çm»—ý„‹#Ù.ír£!µ¡C•†©›¬¿ióy“‹‹IûK¡¤ÉH±$ÕnƒX‘eí/ñí™Ãv͘Ç»Oñ\ß—ûf¯/³ ±C¿qµ¨ëÓKçr“bÝ®µƒÉX‡9r‘³N‹„Ñcõëwý±Û–Ó -¡WÏw¡oÍ-ï"õ¡ý!Ë’×i—¢é(Ùc—W·v•­‰KÓ`½+ɇ¹tÉ‹•Jѱ¥¹[á)™·^Ë“ï¯P‹«v•šó+û­¡<ƒˆ¯„ïuÍ qÑS«ñ™|Í÷÷vï:Éš­Z‹®³~¿DÓÉ-ÁoÇ—H‹]±?©³Ç.ûiËr³½dÓÏ‚ÛhÝ&¥Ó<³˜Í…F™,… ^É¢÷z…eËQÍ0£¡Ón‘Uã¥Ù|ß=›b½3»šï}õ9¹ ‘¡Ë™›Nû¦™l‘›Ï4÷¥Í »ƒlõ[£:åýl›1²Ç£û6Ÿ|[™ëû|¥\…,‹xïùýmщµEÛ;‹ÛgÓ²÷ñ£FýLÉýr“f¡$ɡ퉧8Åvµ9³™t=Ç™×bùMƒ3ù ¹ד¹_ï<ñT«‰R×1ͨ‘˜¡{ŸÏ#¡Õs“t»h›‰°¥ÏdÿB*€á¢û™·ƒ6Gá@á ñýÉソ -¡ ýᯠ³CÛ¯„µwÝ"÷IõcÏ¢Çl»*»,ÿ˜×#Ãé‰õu½•Ÿ`­µ@—qó›§&›^Ùn©8ûãuÓ`åLÿN«"•—·Y³IVÏ,µñ -?ƒ†ã•.÷$Ó>ÿ¥³z“¥w‘Cï é‡Ñ7ƒ6ÞÙÏ9§ŽÝuçVÁaƒ-›;™IëO¥­ý¯™LéŽç]“7ã Ù&½ǃ»œ¯X‹ »%­Ý«ÁƒËzWá*ï,‘™«Q™ Ù"ãHýŒËé…ç&§f‘]áÁ -É<ß\…'¯€ËŒ…”µ®ñš¡E·ƒ‘¥Wƒn¿h…C™³ªß±Ÿq½eÑ=—‚Ù_ƒ‹d‘²é!ó(‰’™#Õlã!á!Ëeùe‘§ëgá=½£“d‹ËXû8õnmù&¿õ#áÍQ©¦‘zÓ¯›gÉH>õ4ÿãg•P“#½ ±Iï"¡ÕÍJ¹a¡ƒÏ4«`P±­Ûz¯®•*¯AƒUÕu©×hõ/Ÿó“×{ƒ -‹Á&•/±ƒÙU›—£²£?“,µ““³ƒªë)™ýwå@Õ4Ík³GÕk·C¯'ë¨åßœ·]ñÿ ©eëåq•˜íN¹c«7µ‘{½*¿c£,‰íXÁsË(Ñ*Ë»bç›÷˜±%Å3û ™±²¡¨±«‹såX§CÝï ‡˜ÿ¥¤ÁýT™ Õ‹—3ÇrÇdÇ«}ÿ³§™¡™Û+·-џ몵£Õ‘q±\û™§I³®½VÅtÍy¹<…Œ£zÍ`“’«Tëý?»ËÓÿŽŸ×SËu¿Š½®Å”»IågË4ë•Û‚µ_Õï–‡éf³Á¯¥ùo©;2ñ_·1éšÃ‡’ù;é,“|‘×'ÏŠÉߊá ‡Ÿ×Q‡nµUûk•Ÿ.› §Š«q±5—·}ñ°áÿš¥bë]¥Mý D«EãnïP»Í4å¤Ùßy™ ÿ«µ”Ÿ½G›9»åDµXͯ°™.¹‘‹……4…‡_íaÉ]¿W°Ë›ƒù8‰J“•ëpÿ‚£»™ýV»yã_Û˜íEÛ?픋x“/¯Ãx¡Aýk•I·qˇ‹•ãLÏ[ÕzÅs§ÏVõ—vŸ¯å`ç¡n¥Žû|Ãß@Qõ¥ß<¿jížµ¦©:‹Ñ–éw¯Cµ,‰±™¯ £_ë¤ó™áJ¥[¡iÛ ÍZ¿€× ŸV¿Õ‘ÝeÇ ó¤§±‰\Ùe¯Éñ"ùB›ówÉJƒQ•­¡,¹¥áû>}Ï*Í5탑-‡û ͇©¥•¢ÃvñÓA­u‰qÉD¥+‡£°¡Ç8ñ’Ý:¯…»#½–—Ué%Ñ¡—£ ¡lŸ”ÏãŠëQß¡Ó™³Éi‘ÃL{ß4á¡™¯­•~“;¿ÿoÝÑQ›`Á†Å6Á%ÙTù=¹„õOƒ”·«ëDõvû1Ç7ï!ûé6ß>ùa¥€±©œ÷‰•pÍO÷M³Yï;©µ!ù¡‘ª“z§_å_»—d™ɘß9Í-¯M›-ßY™iÙÓeÃa±FÇ«‡N¿lé Ÿ‡·Ï‚µT·†ñ¿ë¢Í›<‡EûŠ‰+ßcíoó@¥N‰z±LëeÝ*± Ù“5Á³Ÿà ³MÛ‹IÁ3¥¥“ª«ùmÿã\É¥³ný¥Ñ$…h«]Ë|Áu‡i§ɬßPë8Ïc—O—˜Í'õk½hëŒñ£»éo·vÁ™ý\­©Œ©y‘H÷@™añ/ཨõ$¿Lµ¢«v§Ñ{ý ÏmûP—Mõ”˳Ã8Ûxï•7›l¿µJñ2÷~‰‡?÷Qû¹(Ÿl‰ÇhßÇx±›»‡:ÑFɛюױ•1¥…ûŽ÷=Ý{ñ?çPãBù§.‡~‘;«9§eŸÓRù¡t£’Ÿ&õj£…qSJ•gÑ—ËñiƒÕn|“i±x]§·ïÛj©¢¯Š…Y¯Z…3I)§,¡9«Bå7ç© Õ&¹;—J“…DŸKÛ E½2¡r›_ÍŠûQÑ ï—×C¹ á›» ±±Ó…ßWÏ+Ç0§ULjëA›§•X,™%Û<‘F³P£#Í«Á§ïeßR™ ÏP‡ƒÕ!ÏBÝ9óŒÍé=ãO¿H‹5±1Í¡¹4>÷gÓEÃZ÷[¿³‹gû®ßÏ“å¿XýªÍqÛ¡Lá<ñ5ã²Û^Ÿ>ïr§]¥p¹tݳ×zãœÇ û³`£g…AÁ ù¥ž¿ž©JÑw»ªë›Ù¥çL—‡¹‹ï$ç?³ óÃUÉ4Ë ýv½ÇÅ2¡†“‰­.åe¡kŸ-û‚;½{£óåŒ5‹–󜙃“”±cŸx¥?åÙÃ$‰:ým§cµN¯™©“$÷’­'«–«„‡›°ÙÁ§ï§»iýd“Kó‰ªÅJë—k‰ ó[í“·J…=œM‡§„·Iï©9ùß3ÁPÁUÛ\¬ùlÁÝsÍg÷i£ªË&­J­¬9… ÷‡Ï‡£…SñëÉB©d…EÛ •›&Û&³í=Õp¡­Ñõ\Å9Å ùvÙuÙNÛOÇ3¡‰—f󪉉‰&—XßgÝrà ±˜ÙH÷xç ·°Éý É‹ÓVáá¨ѲÅñ§áuço·Alï•ѪÇ­Y¯h—)ýçA³ƒÛ…K½‰…Dý˜ý>µAÛQÃFù›ý[õ“Ë<ñN×ûo¿Ž™\•yõŒÝ”é•åŸߥóB]‡ÛZÓwÝh‰¨¿zÅ;ßBÙù°Í/‰`±Qñ±ï¡…oí¤çƒœ¡*ápÅSÅŸǬµ&¹†ƒ–ˆùxᓧ¥µL÷„­œá¥¹QÇS‡žé>×rµ.ïR¥v‘•Ûÿb‡®™HÁ9õ-»¦Å„»ß’¥LÇHÅx¥÷¬ñAÉrÉ!˯$Á©+Ó é2Õ¨é¥õ'óp»”™4Ç©—C£¢d±>§uÕ‰€Y·ˆ±Šû¥×i…c™¿»—Éx½zÑfÛý±.Õ3…w‹²çz‡Ë}¿T»J³L£¤ý_µ -ƒ«³!í'÷L—w‹£·‚äµ=甑^ß µ:Ÿ_‘%ëvË>í>Ï‘ÇX±*¡“Lé-Ï•×W‡‹ÁŠ•ûµ€Ÿ ³tݬ¥>ÍRçpÛS«%£&áj¿¯¦Ë'£u‘ ß©Í–Ùmÿ™á1­GŸÿ•Ý¡ÁŸÛ«I›aÿÓ;Ù€¡ -õ›ÕoÛd›Í%çZãcÑš‡ÍB‰B›}ß…“C§ž‰•ñ[ÝZ¡b«dËß ·‹Åk——†‰?ךƒ[¹Ýpצýó.ó^Ë6›1癥«žÉ¥ÿ¡‘e£•_åaƒv×<­ ó1冷iŸpÛ¨Éù¢­…Åhí -Z•Qý³=ûÓ©ã -Û åáaÁi­óiÙ$Ë"Ç·²óÓo¯%ív¹nÃy‡ ­PÛWípû{í…¯U»>Ó/뉓“}•‰É„Û›Õ µ4­ µf’ϧZ­}ƒ ïI™W߇ó™…X:Å®ƒ±ÇB¥ŒÉŠ¥£Á¬§`“ÍWÆ£EÍ÷¯÷ù“ÛIÛpïý‹1ýQ¥z—n¯EÁlçcÕ,ñ¬Ÿ…‡Y©Ÿ¯/í¥Çg»s÷ƒ—Á@ó$ñw›/÷U«(½!§ µ§£‘v­%ψݱc…jïªÍ û"»£½L“W¿¢åŠ‘ý¨Ÿ˜ãŽÛ„¥Yõ}ÕˆÕG£•ã=Óhÿ—Í•­£÷ž¹8é†÷GÓ$Õ.¹’ëc‰S¡5—0‰"‰F›0µ{Ó —³ å'‰mÉ0•Ët¯n‰™:…ÍœÿHÅX›T³a4Ň¡¯ˉ%µŸiÓ<«¥k៩…Ý}‰Ã&ïU^ó+ýÛh—Š³3ërÓ·^Ç¢ýí©~§M­³¢¥}éù Ë)ﳧ+ù>›¢‰*ï‰ë¡ë…Õ…b™™¨¿'¯‹Ï/­VÑqÛ£cÏ'É—Ç?ƒŸÿ\™h¿ë_…šÝç=­4á‚÷kÙa¹Jõ)’¿i¿EÅg­=ÝŽ‡Y—å…‰ƒƒ"÷bÅ‘‡¹vÓ›ó ÷›«>ñ0Ã5Ózá™—u½³…‰ÑLLµlÑ!Ë-É€ÏXé©ÿ…÷¤åQè¹—¯N›•N—ˆ­{ñfeŸ,½.‹0iÇT«V¿FÉgÓ ·6…Z«“S¿œåN½N©]ÅG·!§nÓq©¯§lÕMã–ÅÑC©T­©…ý@£U™{‚Ût׳—½—ã™Ùƒ•—Iû˜Ço ÙWP³'݇á°Ó)Ë…lã;•&Ó@÷™ÕJ‹,õx¡Hù<Õ‘‹4ýz$½Ñ~ûˆ‰R¯#dz—•±Jõ–#¥±Z@ÑÓ0ån×…Ó§Ù ÃWËkµ]ýÕ/…^É'ш÷ -ë4ï‚¿~ -‰j½;Ñ\Ù5û?¯“‘©óëFÕ5ã|£e…O•¥© Á\ß_‹2¹•3™SïVÍE¡-ë.ýãtÛYÿ ÁÛšÿ>Ñç­Õ¦¥ ¿.Õ©é÷•í£‰8çŸûUÕ—Õxû•û ÿ‰9¯õ·±ïJ‡‡Ó±¡UŠ®õ«“‰Y¡… …ɱ¯&õ—…]P­b‹n¯Dé{á-Ïû&õs™“Q«G¡«‹Ÿ½=û_Aµž•SaÉYé§ݨƒ ¡ÕŠÛgÅ[£BÃ:ûHÕ‡Ëy°‹mSÛ>—ÿTáC°‡…v…ý›»m» -ý±¡ŒÉ­§£tá9·0½§'ñ–ñ‚û…³í™ë§Ñ}¿:Õ¥£'õJ͈û§Û·E©I‘)í]±b׉¡G¹R‘­‰³,±†Ù'«·WórË^§9¿£á½ é–®Ç'‘£ õK­;Ý‘›*™™‘E¿"Ó­“t£)µx‰V—¦““·o“›•“9±§«,Ÿ‡fñ©¡‹™ƒHÅ&ͦ­F±„¥¦Ûc›z÷Ùá¿ ×µ©M¯ŒÅbÅKí{“8§wŸ{é/Ë2“_ñV¯0ÝŒ‡jÕ -É%ƒ)™Ç4ß—¿aÕ0åãTåH±håñ‘ûMëR³*©NgÍ@û2å?¹{ûvónÏÿv…+—|í%Ç—¿@«åA³€ñ ¿­žßrµ‹³©«ó}ËG˃³Vѥݚ爙õÙ[Û¦‡4õ -É¡0Í!ƒt­³×=Áœ³uå¯óo¡d7鮿 -“Ïf“‘¹y× ãNí±“±:Ï!á©çDW…§ÕAõq—„Õ±õ5‡¨·¦‘©Ù,›¥›tÿI­$çCù¥ßTå°‹P÷`É,×)ùY¹X÷Ÿ£‡ÿ8±7‘?å&¡X‹—Ç<ÑVí÷"ãÍ µ$Ë›™»‚™_Ý|fj«²õ@`…MÕ–Ï:~¡ZŸ<‹ËS˱û€ý¬½põ>ÃéH¡oÑ­³+µ1«o•…¡¦“xã)÷,Á—ÿœ÷:·'ÇF›8Ï -³w&Ë£åj›–¿¤Éá é5Ÿ4÷% ‘¥­sù‡Õ+郉Á»)ï6¡—Õ¢—ŒfñKÏ‹:£3‘D›bý™ÏYßhÏœÉP§G¯<³SË1™;Ó²Ãd©P‡aý+ÿE‘[ûVÅ:éUïçU‹¡ç¡‘.×IëZË%2±|çW«‚É.‡mý…»o»†£†ÏG…p·¨‡”ýÏ^ƒ=ŸÅjÏ$õ ÷•…›— ÏiÙ|Ë‘Í}LÃ/å:Ù«cÏ;¹«ý5é—~á£átë{¥%ƒŠ¡³Õ"Ÿ@…i¯¤¿—#³0§~»°ÁRíý)ûgÕ ƒ&Á«Ý+ס׿8×ó*™*‰H•…{ßa¡8·šÁßL¹\냋!‰ƒpµœå-½žùI•®¹™Ï—µ†Ù½Žã¯µhù©4¡+³\…ˆ‘žÓŸñ­Å‘ë*­Sù‹‘Á^¿OÍ‹~Ùß5¥gã(‘låݦN»+ç7£+N×”‰¦Ão«*‘J¡WÑŸ“‰§ç3ƒ(‰gŸ}Ÿ~™Ÿ“ݪOál³Q}åñyÑß„ó­›…žåIû‹·.ù\ÇšÑ -É’“¿fá"Å°߀—œ‡tÑ3½Œó -£*¿$a›6³)¡7ÉRå÷6åk»Œ±~ɦ¿¡£ŸBùM¿k‘€«Ë…»(T£HßÕqŸ!×\Ýí±½‡ª«l‰0Û¯ãPÓ®£ ç;ùë[›"ч×2ËbÏѯ‰˜ýK©ÿpÏzÍ¥·B玷““«Ó%©`½[÷t…\ëL“·w½@‹U•2¥QÃ>½5“XóT¯và Ç6Õ™ÛK¥FÕ\…8ï-¡2Ç)ïSë—‰ëy÷C“.Ý<Õ›Ù*Í’™XéKÛy‘&o§ç«ÿtƒVýY§ ›©éIïEÝÙ’çiïùE‘#Ç ÷8Û‰—‰±40Û`›5•\Ù¢—tѽZ¯˜÷}é?ïTŸ:ùŒ©çGÓf½k›Ã_祗ùå)R¿•Ë+«¦™?×ñeï[ÿ¤‹…½§§Ÿ\¯×3«¢Ý>ç¹Cã€ñ”Jé7¹5ét­zù…‡³{å ã{ׇczCã Ý›Ãs“–váç/‹Ž‹ ½4 ‡K‰5…e…,ï(«¥ïtÍùÝ\ý4á§ýBÏH«É Ý~ãF±ñžógóA©S—®á«åhçE‘Œé0Õ}£.Û«ïX¡Šá#‡AÍ7ÁdÍ1©u‡¯‹t… ÅHÝd§gÙ³Ómçfßã ÏŸ2¿e™¯›]¦ã*íŒÁ §ÉAý¦ÙžÓ‰Ñ2Åá&ýHíl©<ë¥l󭓯ߕ÷±ÉC·÷1ÁjÅž“aƒ×›IÁňõt •†ïD÷§û­§pÙZ½˜ç[Û"íQ‰ë\™†ÃC·×sÙ]í–‘@«w‹Í‘BÅ©ñ‰¹©‘Ùyó‹‘b÷£­+ÿwõEƒ§ý†›Gý¿,«§¨¡eë‘¿UÁ˜Å#‰#·+±£9“N»xƒ©¡•s“ ©Š¹ý²Õ‰=½jÉ+Ë®• ÿk›O‘m›-ÿ#…7‘`ý„—G+õÙxñ ƒBÑ«íA·¤¿ù:™K¹,õY©&ÅÍYãWÛ“å‚…_©ZÉ•Û™תƒšéEÙÝŸr½ŒrÏ.³7‰lç ËTÉ~ɵ«·„ù²åFÓ¥ÉEƒ õË lå>ç#åY™eõ݃ɋӤËi÷vÙKŸZÙã§qõǦµ £¯“'Õ»5Ño÷r•õGë­›˜“0ÉTÏsÕŸÓŠë&Çù­¡Évù€‹Y‡©“@ãËës¿R/¿‡Ëœç^ëžÑzbÓ}­¡Ë_™°å6•‰dÅ¿ áVá—’ñ‘›Ñ ¹µãhã„•“™ÓSÿ›$Ç®çFွ?ñc×"³ï:ó6ñ…Ù™ÛwçrÿJç©-•HŸœËv™£‰Ù±«­³“±’%ù1Å%‰$ó©ïç(›«ûžß%óUéOÙ%Å`¥\ƒ«§ùuÙAÇaÇ&§T³N‡=«<"…G÷N‡—÷­Ç+㩽U÷™¡cÛ®©•Ù†ÕvÓ2­á€·,£h[ßp¡µK³^‰¯í÷&Íz‘"©‰ë7÷'ék±j‹šç0ƒiç1«§ß ©.‡°Ûsã˜Û‡óÿG§Dép±•›h¹T‘oëšÇ岇÷A§dç› Ùój­D©ˆƒ‹‹8ÕùnÏó{í—Ë­¿(±TÝN·*Éý”û~σÁ~¥Bµ˜…€Ë‚¿5Í6ñ3õM÷iù³¯‘Oá?Ÿ «Ï™ý¥C™Cõ*ó)ÃpË ýyýn¥‡³›¤›’áwÁ:ål£>›ªõ%³2¹³”—!͆"¹¢õÿ)õ‘—:OÛƒÇAùR÷QÏ@ß2‹%™$‰<¯Sñ~ßš§Vù+ÿ9Ýt•}™¢÷s¡ñzƒÝÓÉ¢E•aùžÛG­€Ÿj»Uƒ‡‰t›™váNç‚»©“­‘¡»KÙE½œ¯ƒˆõ ÕL™áÓŽ™dÅIó±Ÿ[± ½IÁŽ™¿Kÿn©žßmÑÛɈ‹(¹–‘VëχÙ0ŸO¡;¹ñ$ƒAï+ÙlÕ8ÝQý¤ákç¢åbé›R©Mç‹•“p±2×pã%í…>Ë‘|‹‰£:ŸŸ±tç -™n¹›4Í£å Ï¡—‹Ï-˜8ÿ*ûuÛ‡‘›‰.áïÓ:¥2ÿ<íYó]õUÏŽ‹Mó…ã¡íw³¡Ã1Ó5É¡ë@™>Õt¥•ÉXýUÇN‘cƒ¢µ¥Z×*ãšµ ß‚ÔŸª¥U¡RÙfí|Ǫ‘Aã+÷p‹ƒ“ˆ÷Œ±D¹£é_˜Ó‹ —$Ù½¯Žå‘»}±‹rí¥ ÝqùC¡/“%Éj,™(탒ãXõ¦Ÿ§÷dÝ,‹`‘‹9ù|õ=£X¡§‹½ñGßkÙpÃ<ó¬¿PÝ·&嘧ñ™é}ñrã±K•,£T·‘‹é\“uåª×,±vÍ#ƒlã0õo;¿Iÿ‘h—W“‘f•(‰£­h‹ªçaï†Ù¦Áwó/•oÉ_—µC¯J™Mí• ™Ž÷‰Ë»Q«\ë®ÉÉ ƒ\וóy‹Œ©¨ÑKå ï{‘û¯çn±SË;åBË…#çJ‡7ɵ×&¿’Ÿ3Ã~ý<ÉyÛMÝ«ˆ—`»TûiÅÝG­ˆõr‘*‹B±P‰;³pñƒÁ›ï#Vù3φ•w¯¹oå0«0‘­Ù¤å®Ùg¥¯÷_ݱ…r÷Yë€ã Ýa£1«[Ùk¥ÃK·X—7Ÿ9½gÝŸ•‰]ʼnå„­Cå©“§†»lÓJ±3ÏeÛ]ÅzÙ^ÁXõ3Ñ)ñsã1¥…±;ýLíD‡\—õªéª]ëˆû¡ñÕ2Ñß$ã£é¦Û-¬‰Ã|±{á>—r&åýgÁ•¨í™&É|»HÛ -Ç%¹¬á˜¯3û ›žÛ²ï\ëŠC‹S#÷R¯ —@ã§ýtÿ§ÑHÅà -Ó—½©/I½W‡BÁf‰¤ùd¿«Åe›ÿz— ·£ùDë¯Õ•ï«­1¥E™xù¤½‰‰óuϭ颥Šíˆ÷“AÏ•£R‹{Á2Í÷Š¡…¥ÿP¹§Ñ ÇZŸLÉ®™f“(û4©‰Ã4Å™­-·2ÝU÷F÷#Ã-›X•+Ù£“?“åšÓœ‘_Çq§Rµ–5“ -ÇUçÁÍ>©1ïZÅD‡Šq‹«‘ý(ÓZ©gÑ5WÙ1£©ƒ;‰TÛ9ŸtÛ°íM™±é ÙªåfÝÕ雹E·¥^7DÏoûd‹|õy¡K£Y©’Ï#ÏI‘/é - -µ'ÕRõ›sÑÍGÁ¿?ó:€½™·¢ó2…[™§jƒ»V·VŸ·3Ñ/ݯµ2™»2¥ ×!ÿD÷ßf§Ÿ‹§ow…¬½“ÕWÏ¥»6¡çMoÓšÿ’•ªû:ËF±BÝK©­ -ïƒásÿQÉ9ù™—4•F©tûœí•|(—Ñ4ÏJ­EýlÅûY‡Ÿé뱡”³lÿ!©—¿ÓHŸSí«˜£Ÿ¡ Í0^¹kƒ°«n¡…Û'ϲåxÕ²ǨõL›•±YóKçªñqÕ~Ålõ<Ó¦™s·»&…J‡ -{½c¡[×$j»EÝ`· ±»dù}•m¦£¬“D×V‘–ÿ³•Ù‚›ŠÓ#³‚c÷Žåù -µZ™¬‡ ›€Ín…fã"Å)Á8ù®Á‡Ç©¹h›‹Ùç$¿ªÙR“ ]‹ ÝvÅ"ÉWñFÕ>é4Ý#¥-¡œã¦Ímûyñ‡ã°áËc“§ý°ÁŸ8ûaåU‰!£-ñuÕ]Á³·$Û†Ù4©é¯³Ñ«£$ó‚ÝVÏ ™‚…°ÇD³–±W‘8Å -é½O…¢ ¯s‹w÷¿;µ‘ˆÛC“3ådá\Ç‚óO笇6Ù®½>ÅýPýeµB‰U™N‹}¥.á[ÅÑB•Ž™9û,ý]É…L÷ÃQÑr­t—Ëù•—DÝ©ƒ9õ?·›¯I±Rµ •°ñUÍa£fÙ/»§®½-éi‹‘™gßOËáiÿaûÇœ©‡Ç`ãm•«W©íW§v…ãCƒ~Ÿžݘ‰ „Ísç±· Ñpa½‡«°Ã(ßD•r‡%™Š§!í»Ž»YÙ6¯R¯*í9­iÛ‡.¯Ót¥J»=—F‡— ¯W¡½|ûj Áª›%ï’ù »[å;—²© ™…ÿ6 ·@›wëXõpµ"ëH¡¥šß}õ‡ƒcÇjó0Ý/‡hë~Á,Á•­–“où¯«LÅ(·U±AãÛ¢Ù¯µ²Õ*ÿ ¥ÅQÉ`— ÇE£a¥‹Å>ÿj½¬«?× ¹"µPã6£Wír…*Õ'¿ ͱ‹§Û[…Ix㨕K×`É»-Õ@¯‰££÷2ÛÑ ùcÁ…í6ÇJ‰{ëo÷†Zµg›NÓ“ï]é]é&ïwÙ8ãÕ ¹™ÿ[Û{“¯áZ»N«#áWë‹s©²»‹€­¯“kÍ{Û¤fû”‡¦éŒ—“÷cUãi›S»„•<µoý¢£ÿK©5—jÛf×fÍ ÿ…ñŒI­¿]÷f·?§X»˜Ë$«C¯ñ4ý'…Fƒ±­Iï@÷sÙoÑ’¥RÝRß³£—ç8Ñ››—ƒ­\£¡·×eÝœ_Õsß…¥‘±"±e¯6‘‹ÁZ‘š¯d§Ý¹Ví-‰£AÁ|ÿ -¿V“¥ŸÉ(§ÿ7ñ±§ ßy½Rí€ÛBÇ„áeµ™›?ñJÿí:§z‡†•i©ƒ©i•]“Fíh6³X©­§˜Ã2Õ„¥§Õc©¿š¥Í—˨‹Œ‡Ùc¥Õjë›@­B™Y›M«Sëå<ŸGB‘Ë€‘#•ƒ5»©çÍ‚ëSñ.¡I³éGϳ³hÇç_§¹#×—çe›7ƒ­¡C—cÙGËOÑiµ’׋vR±“<Ç.Óç-Ÿ¡Õš­÷\‡l†­Ÿõï“Ó†›¦á‡¹3ß+‡«|ÙKñ!ñû.é‹ë–™}õ‹ÙLñó£‰ Ñ-·r›B•D“éQ¡=•ó9Ñ¢ãr™Œ³K™ªá¥SÑ™¯ÇŽ‰iƒ/ý/Ó¡«¯Tõ§—]ù?ñ(­—«páÑt•«Ïyï„9‹Ýñ\ùËQFÍÝiÙDë{¯FãÇzljñl³„™ˆ§ Ÿ¤Qß*¡¯÷/£éCÏh™ ±Ën‘ §$½šïjÙ=‹DÉp§ -ƒ;û#¯rãª÷h·y垉Ûlÿ^Å^—KëtÃ}Ç¥Xù£éc놳 Á‚ϔǻ ÍN畬ù0á–­k³’«O«gÙ Ée‡í[ñmçb¹ŠÙ°Ÿ¬‰¥‰fÁé ñOṓý8·ë “¡@ï»/û'ïkë‹ï1µVÃ…ÇWç¿¿G÷ Õ^“‹¯Ÿ‰›ƒ‡¢÷ÿ±­=±#«K¿JÛ—Ílý7ß'­5¿pŬ˯«6—©“eÝMß`‹×}¥„×j÷ˆMÓÅBçh£¨Ó+ý¥i³3Ýbé¡eãÃc¿0‹ñ¨ãG™€·(™+Ç–§’£‹¥/çI•‚»¯éN§‰Ã™…@ÍC»åãkå\±”ÑŠ±³Ïp‹ˆ§}ÏdË“‹ùKÅMÝ-É”­[Ñx‹Ýå›õ¡µ«M׬ÍP×%ázǤ³œ‹Lë+ŸAñ=§Qó<¥deÏ͘Óu‡[ÅF¯^Vã«ÿ¬åÁW³ˆµY«¨ƒ«iï`í8íÅoíP¥cç—ÇŒ»ÃD¹ŽÙñ7‹aÕ±õ¥ó ˤÁ5¹LõVÍÓÁ‰…x—^›3ß#µFõ¡£]í‹çŠý6Óxï_Åv‰7ç>«^»1‘£ÛkÃ"ç•…-¡QÁQß~ç~­0ó¦yÃ!É÷¢ã`…•lýCåõ9­e™,Å ©ÕŒ™¦ß!÷]»¯yÙ-×|㇓—•u¥<á,³9±mÉ@ãE½)ùfƒ¥¡“Õw¯’©Žõ‹щŤß›­ÇoïYå™ÅëwŸI«h³ë« …k‡£Ý;‡gˈ«sóá%Ó -ǣ˫áf¿g‹O÷lÇ–Á*ÁÑ#ñ£‘UÅ­·9·œï%ߦËg“ @»Å~­­›j³cÉtÁ{¹HëT™Oe½^ƒ7»v¿…‡x‹‹ã Ëp”ËBód£¡|åÇ1¿ªµ°õšŸ » ÷P‹Š»@÷¦£—LѨƒ,Ócùë©Oó4ù5ùŽ{¹mµ%²³ -ÙJ…œÑeçT‘‡‡3‡D‹Rµ~Ó½Ÿƒ˜Ó9É £“™ó÷¡…x§)uçË‹³ íª±°£›¿‰Ù«×5óÿ¹9õFçó¢±ñZ»§µv­‡™ ƒhç%ñ@¹²×.¥5á²ÕÉù[ùzƒ<ùqó=\Ñ©¢·®—ç:ŸoÝ‘!ÙYÅ*£œû$Ó€Çf½Aé“Ë–ÁHçÁ—b郟¯IÓ‰©ÝO©˜ÑXAµá{‡pïé Í=ÿ'»P÷¡%¡gõ×™‹•6Íõeéžýi¯·põ¢ƒ…¥z“Hí§£ -ïFåƒ÷–«¢Û€ÓC‘\뇽%µ#‹\­ Ç\•`‹ÍŸµbûD¿„á3¿±ãYí‚¿m¨Éw™0•htÃ\¿^û²©QíáAƒ$‘Ù<»:«)Ý&ÝYí²…R›»h¹w™«ãËP·dѳ‰[¯aéÉŒ‡áQÏ…Ï€¥GãvñX­KŸ%á±Ã,£–·Zljb÷—Ûo±®Û’ù‰ž›‰‰3‘gÓÿ]¯|ƒF³5³rá¬á¯ñ½ £Q»Ý5‹=—šÅѯ±uñxó\ûÊç°×•%©U¯·‡³;•#•-¹p•ó3Û.ÿOÇR³Uýå݉·#»³±d¥#Õ¤¡¯;»± -Ý 0ß8¹7Ã@ÕV¹˜£<ÝJï¦ÕK©,³™D“‡áOù‚ŸgߪçuÕDáÙŠ÷Å=§ƒélûEÙœ÷y¿·÷ Q­…"ó"×të-ë ³@…sï±ù'×m³B±^í4ᆗ9‘~§|˟벡ˆã?ƒJµƒ1•‘‰1§±0Û×óŸ•“Åœ­6ÿ~¡•áXûJï.Ù ïxƒY­MÙ—Å›·Œ¥©x£õ‘„ßA«fýƒÑ]ómïûŸëJŸ†Ÿ2Ñ”‡±±_ë ¥"óÃ+·› ±=ÓÁI©ç˜ï›ûë^‡–ñpÓ ñ-ùZ³žóˆ—géùbo“R«zÝ°ë3Ý)µR×9Ó2ͽPÓŒÛÇ¥ûƒÛ5‘˜!ùŸïWÏ«õ1ç½dÅE×: ¥nåt»Ázw›­ÉõSÙ“× ³k•b“>ß6ƒ8ÑYýßSÃ[£ÇkçXÉ/éV‹6Ùϧ¿ éÑRíbë„ŸW…!Ým‰Ÿ­”¡‘½fß?åãw‹ym¹qÅŠѤ‰yÑPó©Yß“Ÿ#‘t׋‡Zá®Ñ£y¹[ó-¿\·4« û±Å1™ý·ƒõ•ãqÑ‹e¹D«†¥¥Ëo½3¡pÉ)õ&é«ñ}¥ª«€û0­7ÛŸ÷má7ÏqùµD›vÑ&·GÑWåOãÿŒ³íL³²ËÃŽ•W¥¢÷)™)ŸQé`Û:¯g¥'½Šù-ŸJ‹CÇ¡‡R­²§šÏ ýWÝfɀ“‰vóQÏK·t­¯tí‰á©ß•c¥ãï5Í‘Ó1Ë3Á ÃA—¡²åƒ£µ^“¬£L±·"£¹s½q«JÛ0‹+Û©•=½Eƒ™— £C©™Áƒƒ¹&™~¹ƒ#íÙ~û‘ƒ ßHñ÷Ñc· ‹±•€ë­l§[ƒ>Ó|»Ù õÃTžÕ‹—§…óH‹oõbÕ©q­¦¹‰£[çj©kýÓ–Õ›Ÿ“Ùi…q‡H¯Pß?ßjß±¨‡›±‘ËEA¹~ëUÁ`³9§²ˬŸCá?íós³­ƒ+¥˜Ž¹•¡áßFÏ7Ÿ‚á/ŸDã'¯_—á—"¯wÉ1€…ý"Ù3ï£å½«DiËã£4½›¥™©!ÇnãÝz‘½¢—éPÕƒ¦­~ÛÁ½Y÷õ£Ïu±}û¨Õ-«xû¹2™1«É5›F‘wëËçŒß1¿{ýœµ›‰­…/“mŸ0‘$ÛJÙrÅ<¿r•)—mUû ù×-ó>ßÉ7½:»fç„ů÷eÏßÃk­#¥xÁ[Ó™ý®Í"ûp£!ߣù±g‰(ó_Ëá~HÓçOßë,¿§ׄÅ‹™!½ ýJ§BïKåiÍe©¬Ù(×ÇŸe倉~µŒã>óD×/¿¨Ó§¿®ÕPí_ÁYÉs…1ïGísÓ‚í­Ñ?¥=ã$‰aK¯…Ñn‘|ÁM•:í«5Ý¡ŸóxùNËW»“ãyÇ“½y·…˜ÍwÑu‹'χM¹€‡I‰-µ5¥×ÍŸyÇm‘káh©nÉ2Óß_+¯‡8—¡…}«‡»7÷ª«ï©ÇÓd£(¹/³v‰±ªóMýXð‡vË©—1•kû%ëd¯Bá`ÃfX…†Ÿ™‘w“wµEýó”×ué‚× —™Ï§£©‰«©©h»ŸÙ¬‡£ù,ÍF߉ɨªý“£Ž?µ8§1džÉlÑ"õD³±kߔ͗µã3㛫U¥éùJ¯Žý…§¿N—A³sˆ½D©\‘SÑ,¿3‹-—2Ý«A‘¦é©„‡ÓM‡;‰,ƒ‹ž¿˜·%»šÓpñãÕbÿ1±@Ûb›.Ï=á­•AÛU‰ˆ%¹®ÏnÛa¯šÕË`ñoç“¥&éýoÁ>ÙBõ¨Ù ß0ÙŒûtûKÿ†ç ±ÅCý‰óJ‘9Ç™wç|· -ÿiÓ‹»åV͇*£›Eãl™7óz±)½¦ÕrŸhݤ“¡ÿ¯õ.­ ¹ Ék™j‘¹«œ¡¢u¹M·£ Ý“…·‡™ï4­ ½ní¯µWÁ åEן¿ÅZͤ©‘Õ$¡»€ÓG÷ Ý‚¹d×Gã±åTό߰5½}õ©°¹³†«R©“—Hᯛ¯©*ÿ0FË9ÏÃm³ŒãJ‘rÑg‰‹E­å•ÿ=­R÷‘‰‘Ï‹jã[“:ŸM™J²Ýœÿ ãAá‹Ñ Ý…¯•0ÇiŸ…ùŸš™Gý É‘½/ÙsÉ‚õ­oÿMï”çxÅšã0åé¨ÕŸˆ“jÃ6ÿq©‚÷€½9ù¬ë·D™»Wµˆ­@Ýlÿ?㥥‚ƒx—(íx³f«mû„éïyÁGŸ­ùƒm¥½ï‹Å’Ñ.ZÏxÛ§=Ó,…®Í9›~ñ)— ïmýr—-­H¡®ÁËwÇ£§¡zÿ.¡ ‡]Ç~•5û*[³¤û+¿Ï µ*ÕñtÕ÷°›®×L±U‡1»'‘n¥åýï ƒ3ñ†û¹0÷Éœ¥1‰6Í—žÑsí`™”Ýëítû]§*ßo± ™2Á(Å,ÿußxï±Ã'ûB·Åu§°Ù©—P…ÿ4ù~Õ_‹¥Õgë')¥y•z¥šéaÛrµ£‚™"¥7½ƒƒÃÅ•‡^›Œëj±?¡¡¡!ûNß»›µHçƒ4é[¿DëƒËm‘ïÑvýÉKÅ_£ Í“¥O“ᑹ -áE<Á“½MÇ5·µŸÙF•YÑ°éÿ““± › ƒw±‹>ß]õ®áí°õ Ÿ|‹#ƒ¥ ŧñ&õHç ­3ßž×1£rñû’ÉmÕ7õŸ‹&÷ñŽcÁ¦™ùñ £j*‰eµ<•Œû\Á#«Ž—›¯eŽ±[ËÍo±N•^ámÉ¥ƒó¡©±l3¡\“A¯‡ý.Å–ïᦩ#…P‹)§¬•9ãS¿bÛˆïל©ÝH¯{4Ÿ›ãI‹k›f‘IÓ6«ÇIé^å^»`ñŸׇ× -Å4Á×óI“®é‘‘õ¹eÛ/‘Z—€÷wéF…a£B¹]µìûT«4ã‰|Íp¿­ñ“õ]ÉI³«§€‡kÓKï>ïLÉo÷+›•’ŹKézÏ<±&õN¹`½¡•d¹gÿ{ýu“ŸÛÇ™·žÍV¡·)ûͲÕª×céÝ .•ZÓ«û¦û!íuá6½„ù7ýhÓÏTµŽÍïvë ‹N×›»8õl‹¯Ù‰ ó€á£õwÕÕ Í+ñ^ùL—ŸÕ Õ‡×nÕ(ç ¡Ž§A‰pç†ë$ùyƒÙ\²‹”­Á-çÉc³jÁŒý}ÁpÑ“é"‘ßÇ/õÓ7“*ÿ,¡E©‹ -ÅU#µI³#±-Ÿ±ÃTÏײãxÁb8“YG—ZÝXõWŸƒ³…ûFçƒ'ùr‹^ëVÙÕ‚—‘¹¿Ÿm¯}í‘×’ÕNÓÙŽ­Šƒ_ÃP“ å9ýˆ¹‹Û£ÅŒ‡‰Á¥ÿ;Ó\׈§0¯Ãhû;éA‘NÏSß(³¨ß|߆Å5•±·:Û1ÝSѯ—¡£ÿ„³‹‹ý­ã/ß–‘XÏRÁAåœñhë/ÍvÁ°gáLÏv«Šù9érƒž‹uå¢çµrç6ƒ Ù}³-¥©•²‹ƒ‚§‘óã<ÛnË”å±Ådñ•…%§”‰Œ¥j³—ª×oÿ…0ß듹Ÿ&ÇŸµjÁ_É8ߧ…W•žÝ7û5…?ûAƒ*Ë[Çu™ã†¹ªƒSÑ‘ ïOƒ¨ù6ŽTÑ`h« -ë:ó†Í «›««ÉŸ‡qÿ®ãÉd•TÝ ¹f¡žÑ+™É>ß‹—­yýS¹|õˆ¡YÛª•‡«a“~‘ŽÁTß[ɇÏ=¿¥·Hç£OÓ”«_¯ëx×°«$£@•uµñCß‘=ñ€‡d‘yÑ‚ùåßG㞟Ñ×N×·fË•P…p»¬ã.½(å*ùWÓXÍ)«‰ Ó_…zÁhÿ¥Vå2³"é~Ýoµ‚ÇÝ_ÏU›:Ý¥‹cå¨ωµ ɯÑTÏ"É-Ÿ£¹•·j“{Ó¢»ÍŸŠ×4Ç=Ÿ¿”±$÷jϦí˦»Xµ\ûzËIË\•›rÇ#ù–¯@©- ½x­,í0¹-×·¯‰Aç'³_ƒù^姵kÝj‡W¥]¥tõŸrý Ý -›ë>6:«Fé ÷¿9“Gù’ÑžÅNùjë9Ûž›YÇ9Í\»<ƒzÓ‘‘Ë™·KÕCéË,ïµ6ñõ®·á2‰ Ç,õ­á›¯½ק…|‹?¡$©i~ ƒ`Í·˜§•Ë]¯~Åa× ŸÅ+Åpë5£íT“ Õh‡y…d»;Á)ó„£` Ã=½¯¡±…ª×Û8ù “+:‡ ûsÁB©>·‡rïa‡³Ÿ•{÷^«=hËAÛ‰™{§(ÍjË.ñ6‡O³q»ˆã¢wõ“!ÛA¿Œ¥$§Y›iå‹™U¹Z™|\K§K·³éj¿‘Çe‘Q©†‘i·”ë1ï3ÓB7¥±³nËÃJXý&Û­õm›[ÛŽñ™›çg[j᪙VûZÃN›‘µ¬ãjõ_¥~Ól‘T»‰r¿yÁ+÷…ËóšÃ`íy©váKéSÕ[ñ«¿éxÃR—³ÙQß¡1“•Å}Ó ç®ã7Ã9ÿ‹«ÏëÿeóÉ?áGÛ³ÓŸ³>&˧›p¯`ј§iÇVý%×DãD¡¡B¥q׆Ý©Ç ã½‹Ážƒë­¢Ó¥aÏa‹]³³ÙjíIëI=ÉMãÃH‰Q™`Ñ“ÇQÕ{å.Ù@ÿÍI§8ñ%ó²Û6­Õ¬Ói‘W‹¢³£ù ¡¬‡ñP±Ù Ámí ƒEƒf—sá8­­Lÿ£^ÑŒ³Š¯1·F¯7£õCç"ñj§åBÑaµ¨ÃSë"©b<Ñ%Ç—–ÁSŸɪ‰¯±ánåc¹¤‹©¿‹ç—¬5¥ù`‰%›ÝC±ˆ© ÿž÷W“ Ñ›ó·`¯ý2©®¤Ï`¯-›Ž‡-Ç€áŸ;óc—[Ñ1½0³±obñŠ·M×wùHÙdóeÿgç\½ ·–ímã,³|…“ÿ$Ñlã¿…‹íZ¿!—\•J(É#­gûLmpŸ+óS§L½,«”ù†ÏD­W£m±™lãÕU‘®ߎÕ­ó#íᜥ -¯l™EévŸ€¹·S›Z£~ó°é;ËR½'Ù{ŸzÇË¢…Váv÷D³RÁvŸÉU¿CÛ¯åC³ó~›kŸ¹YÑ ×£ƒDí,‰X¿DzÙ—‘ƒÏ5­"ɽ‘L¿Y±­Ý?‰aµG×?“©¹‘•ýRÍ]»Oë2ñ‹Çå–Cµ„¹×€ó¥¡q±s½­‘ë˜á:•™Ûe„Ó³Û¡Ó4÷T‹³— -ß -ƒ|­™'É:µ±±©©wé@Í -yÁÏ{Ó¬›‚é—ý~É[RïM÷±y…–ófç…Û Ÿ°éͱ‰ç‰µ¹$ñù˜˘É“Éqó'å}ߤŸå¡å‡ç2‘4ÑO¯ -á¢én‡Q½ Í ³°¯!­ у©FÍ‹™]Áy!‡“ƒÛ¬Ã’½€Y©³Ÿ'­ZÇ‹½‚¿#Á©ëztûŒ×[Û=8š1ßi—¨÷ ׳罪ûe§{Ã7‘v¯GÉ»­ão÷zÕ‹‡û©­Û…±µ–ò‰4Ë÷où‘Áqï*ÍM›m›>÷‹ëMË’“ŽŸ)‹VÏ)ÛuE­UÅ•[Í”Gѧ©–£\×áDí}ÓPùÓy—z¥–ï…¦‰>é°ÁNű‹Z碌$¥4©ÝÃG·©S³ç.ƒŽ·xÏWÅ“Ϫ³Hë`Íiùiõ(ç–ÉŸRû^ƒ¡ç‡Ý!­¤Á²Á]÷§ý½\0½áï0­ëY'§pýë}¥’és·{Ó•÷<© …Ÿù.Lùó‡÷œß{‹›\‘ã ÓO“¢Ù³]Ë™‰KóXñ¢•Š¹í É­—”‡s—<å4Åfÿ”¥(ï ã»M­`¯9¡"Å«­w™QóqŸ5‹XÁ í•õQéhí®—•ŸK‰C‹¤6ëi»õ~¡<ÿÓ=©'»?ç£Ç…é(…&ÏE½~™bÑh§JÑ¥½°Á?‰x‡0¿-Í3“Vç7ÿ`¹lƒPï…N§Sá|Ù2•Ñ³˜™§Í:ÏkÓ?ÿ&Ÿ7ÏCý‡Cíš­(ÝåM»ï°‹@£v§m£Z…¨—ßbµ9áyÙ¨¡±ÇvË„ç¯HëWÿf“€ûl™o…«í<Å‚¤»‹KÍ2‡e÷9——¯õZób³eï&^ûÏg÷‰híSßÇ·O^ׂÙ–¹š£±„.û‡§O÷*ídá_ïcÿ(» Ù%™‰8‘s„Yý-Ãj³ óFñ1•íµiÿ†Ý­µ-·5“—›¨ñQµ¡ç,ƒMÿC•E¹?¯† åÇ[“nëm·QÃM•UÍU¡~ÿVÅ¿…¡Õ6ï©7Ç-㑬ÍK±aÿ‡ý0•×;‡CÝ—*ÑS£F•¤±z§y÷0…máxÏr¯›óCѦù¦ÿÉñkŸvÿ:…9Ñmë!™–‘PÏ’ÁJ³mÁ‹á ¡'åËU9å"“hùwÙM©½H×UÕm‘3¿S• ™²»Dµ7…ƒa©Eσ?‹Qõœɲ£³Ö¯"Á”Ë/ƒI×lÏ.»¤£oÅ|»w·¡ÿ¥rýŸ‘'ßuãaÇÉ}S¡h×7…™Ñ看¬ƒ.ó%Í…½a(õ7³‰¹Fñ˜ýsÁ'¿v¯ž‰«õ8ŸŒÑkí›Õžï8½’ó?Ãt…6ƒsŸ ÿd©Hñ<›­OJÙvëfûïAÁ=¡SïfŸ‹å]ÿXÅ.³$Ñ‘…«bÙbµ?ý!‘aÉFùƒ²—… í1…­ãM§s™'çH¹!×y›éË“Œùš»tñÙ+ÇY‘,»ƒÿ‹Û–ûG¿ZÁ„Û÷®×–g­jý‚ý9‘±­rÇC«•ß­‡F—&µŠß®³Jµ¯Át‡ˆçlÁK¹Ùš­ŽãdÅ{ƒ—RëKƒN×vÉï)ŒÑÃë(Ýç¿Ç(¯¬¯ƒá‰¡˜í˜­2³~ÃŒí¬½oûRà <­•–ÇKÚÇy:ûå(¿|ᕘÅi….›PñnárÛE™6•›ñÝ®¡Á•jó‘zý§Á;±Œá'…2Ç!™q_“Å…éWÅ¡‰ZíV㕽]‹ýEí7ïo£—p»|ÿª¥Ór«³»p½8‘0éë°©cÕƒÓƒËx÷5‹Wù"óÍr‹>›+½±‹†Ç2ƒ¯Õ«Û©aùÛL픯Ӟù›‡L¯VÓ"Û4Í ŸFÉš½¯jVõ"‹¨×år¥uù@ë; -ÿ3±÷©¿2£ç’¹@×TíR¡4«‰ƒró• é+‡U‡¹6ñ¤½¤ßE¡D§§÷{2Ý=—VáU›‡£¦­X½XŸ¦å%…)é<ÿ°»{×kÁ­÷S£S§¢ç³4¿=Í•ˆͳ¿6‚¯[ÇwŸEÕ:ß‘Ù˜ç Û‹í± åyÉž9ëb…Ël‡•Ý—튛¬·€õhûí2ÿ Ó*]Ï Ï&£V‡ ËKû£­í~½« ¥)ó÷B×^³›éZ¡aõž•OÝ–»¢õ’«¥@™-§…;¿4óŸ?Û̓/¹ ³Ï“’“b‰D‰†Ù­•e¡O«Nӧȫ‹µ’¿íOkRËfÝ“"ñ]ãbã4ßeÁ<Ý„Õœƒ®›ˆ³x·<$Á‡}ǘá}­Qå{îÝ(³ÏMÑ9ýÑ^£ÅŽ§³íÛ}Ý ±œù4—.Ù)£7¿+Ù ÛR›±§%£J³WÙc·e…g½ˆÝ]½·\åGQ™u’›Ï%¯5‰ÿFųg×AÇ°¡6¡’Á1ùsÑù¨ÍS—±ïCŸ¨Ï(¥9­q›,¯Ké@ãV‰'·g¯•µué:ãf…`§ùS‡"ë‡<×K¯oý·¹U=ÿ ƒW••›«“s©šY»]á ©±ëß ›…í?çq§HçPó§Ç•Á’±Xë£õ²ùêéL§“áI¯+Ã*é’ŸbÇÍT陋}¡ãùQý -óŽñÅPù„Ù¡Ï®ù§çíß«Ó{§ˆ±_»®ç¯ó‰µy‹°‰k—­¡ŸTËM‰G‘³MÙ9¹ž÷¨ý­)é'½©Vß«¯‹¡.¡(ŇŠ¯Oól¯“™•Õ˜‹;¡3Ÿ¥“‰Ÿ—ù׎‰L›„ÿçtÙ„÷ ѱßC— ­fŸu©©•?å¦ßUÓ„óžËNí.Õ`íi íg½Ã3ߘµÑ€ÏF›³Ó[ßN‰o×±¡fï‘‹3É¿Q}Ë•B¹P©¯¥ã-4«eé3W‰®Çsé1…$³.©Óa©Ë{¯>½7ã—BÏž÷”¹œ“gñœƒ2±‚,åˆÙ›•³‰½KƒŸ(Ç@«@õ‚¹Iý•ñ¦Š¿nµ£M“]£¥åo…¤ýžåk÷ Û¥­:½Ó˜ïl£«¬Å¢ݧ¡P×Zã9ï­ßd묮‰á(¹µ ד‘dɧϯÁ±'¯k÷Û~›{¯\‹b¥²­†£"¥”³¡¿©ÕTó˜ÙPÁ.מ‡oÅwó`¯zËJ©"—i‡šÓëB«’óZß&¡`©6Çû}¹1¡Jù#*ÕBÕi»c‡z•L…¢×X‘ïõ©ÙŸÿ„½"µ…—a±¡õ†ÿ+“1§5¹×F»±‡égçž­ßvÍh±÷?«tA÷Z»\tÛi±pOå|ÙO­¥!Å@3«Œ}…•ù)ïu‘œƒ„Ýž»u‡ ·mõ+çyH¥P…­Ï„¯™^ÕÍLßlÅ'›…\Ýn­>¡:ñ—½¥á”§¯éd™yH©WÑJ»_ѵ;Ï­ŸJ›'›ÝÓjÍÇ:»rÉíœN©[‡H‘ŸG‹"±qém¡ª‰-Í°óLцɇ/-”û‰¿Ÿó|‹‡+™£{õŠ»kÓs«;ë§k‡Ã©lÿ—§µª«Éa‹GÝ%“ɉËhéyåR«ÅV•—£ÿ…É -­/׫Óv±–Ñy½‹Hµ)Ûç!ù$±£2›Aý€ÅŸ Á£“Z§‚ÑNó–‹[åK©BÍé)‰±dÏÕZ³(瀽C±`Ñ>Û2É–‹’µ>³š·nã@é|n—{µÅ0ãe߈ùV©s½§ñ:ûn§‘†­p‹­³áŒûbùµ|ñHµ+·¥ƒÓLéRå Íu©o¡›n£”ý|áš"¹¡ƒƒ“Å8n‘u§û[§«¹…±Á‹hÝD˲Ÿ‹7… µ“cÛV«!פŸw¡õ…›u1…²Uý‘‡¥Ë …„ÿ‘³/ׯӇѱ¬“\…³¹}³©í+q±¢ûÁ—h­cƒ!œ‡J¹ —eñ­_—>'͙瑳Ž·™£ÓYó,í¡ÿy±iéu³EË7Å¥ƒk×BûS癧?åp÷HÍ(ÿ›¯«ߟy­ßs«Yû -á§ïh鱿é#ÅŸËY›‰Ž¹­Ãg£„—Q“UOéq׌ýOÏ}‹_·•lÙ•‘xùªíf¥6™˜ý,ƒy¿í¿%ƒ»’çk› ÷uÇŠ£ÇbÁ0؃d¯.ïp×P©›ý:É™ɆÓ뻡³±§ª/Á4F­|åJÃb£l¥•'»¯ˆÍHóN»¨ÉSlj)•Ÿ6ͬ‡V›(ëEËså!ë«“§U•f­9¿¥«Ån飳ݓŠ‘2¿°‰C§4×6‡b­dÅ]ë=å$ã~» ÉOÕQÿ­‘—_§/©0Ý'¥|×¢‡9Í_Ã^ãsû°ßƒXÿZ‹›£6µ‰µ3Š·a‰„‹ó’¿²ÿY¹±Ý—Y»j‘ˆ»ZË#ñIõ°õ±ËL­„»A¿ ¥ ÕHƒTéÃl¡ ùFÇ^[¥ ¹'‚¯ ß"‰ -…5Ç|¯uù%¹ˆ‰‹Ý3û7¹‰2·‰fË°¥‰‰Nï ±€¥;Ññ|×™«Ëj·>õ‰³“ó Õ¯‡­“ƒ»¿ ©2› ‡§@mû9¿o« ûñB©K©¡·—%ïbã…穵¥óZ¿›ÁDõAËá’¯£›Kßnû—£P×¥ç­vû×~ãí*Ù>µƒã‚×0û ‹TŦïi»²ó¯·ƒqá+ç@žïHßK™®©óRÇ;ƒ]ã—5Á7Ç”‘‚Ÿ·u‰¢ÕŽ§­Ÿé”4××¥D™‡¬ÿ€éMÝ…áT½«‰œÑAŸ^«—ŽϬ·»aÿŠûh·/ÅM¥{ó8ã…nõ ™[¿}§E‘pÃXå{ã‡"µné¤ר«™£0Ãÿ"Û GÑ6ëk•;óP§Ñj¡¤¡‹ÁVáoÛŠ“[“›߬Ÿfý’½†ÿr‘É ËÍ,‡!ï©R‡TážÝ8Ÿÿ–Ý@½1í#«Í‰÷é¬Ùz…’õ^§ Û_ñ9¿™Ï¿¬ýAŸP³6³y½ÁƒËFÙCÅmû¬¡¯«&•»«·P«jÕ§#¡m“¦§Œ›ß.ýb¹¦³¦+Ó’Ç"åZë݆“TÅ·~ÿ‡“r¦É*Á­§<·s»™ï=Ÿ‘Åž³>ÓT¯?Õ“£¡š×•C¡)¹B¹AÕY·—á]ëhÏ>ÍA÷EÍ©éeéD‹¦­ÕÛ÷>—°å,©}“-ý©¡á…“¡}Õ=å£Ëžý3Õ#ß^éŸá Ó^×ýx›DûÙÓ¹je£5¯ËŠÛœÛX˪ßQŸ‰ã”“Pó… -ÝLÏbïͨ¡w£ ƒ½vÑ¿q›C©(—N« “†Õ°£š›Qï~íõa“²ï®õ¥µ¡j»‡ë¡ Å€‘¿)ûC·RåSù”Ř“Iù«¡™ßj—íC³bÇ -DZ™Bùu±£×Y©ù2‰—Õ®Õ‰ÿ/ñdû÷.íñˆ¯b«®Ë!ù ýŽãZÃ*«ª÷Éz“=•¦o‘«»ý^­NÁá0ÙX³ ƒŒá.íJñ`çYÓF…:×]ë‚‹ õŽ›— ÝI“MŸ/¯¥ñTýqë’õT™F{…TÍ®ñ{©%‹/ó®½û­?›¡›Ít½¿ƒ©=¯ª‡ ¥÷ñYñ ™DËrÝc•$­¥éˆËDµ¹”Ÿ®Ūƒ}Õ”‹»¥‡SÓ(륱6í/Ëd×Oßz‘‘õ™íŽï¯i³ã#á—‰ é½Jµš¹ó§‹Ó!Ñ¥£ˆ‰M«y—'é¯Ý1õŹOƒ©j_½iÏûcõ!í@á$ý`½²û«Í­T­°»SÑ_£½—¤õz™A³&n¹uÿ¢Á€‡$!åw«+c¹£Ë5Ÿ*ýF…—ùPÉ=Ë:Ÿš“˜ý{ñ>©¹ûƒÛ%ß ¿³8§bëƒ%ƒ@¡V£i©^…³í$—F·…ÑåvÙVá4«:‡5Á–Ųõ2õ„±ïsñ · é™ñbÛ#É°Ó•"‰c¯¢»GÑ‘›²Ý^”ñ.³Ç{‰n«8ÑDO“éÉ{é€í"•”——¥Iëá@û`û¤“„Å—Ù -ËãQ—xñ,µO‘÷Vç*Ï1¹xŸ©×Má;¨Åc ׃µ[ÿý Û3Ù?Ýx·«¡›q«/ÿ}ûw‰•„£xÃBÁ¢·‘R­«PïBSÇ ±­x™Zé£k«.³T¯ £|ó×+×xÿ-¿—·_)ÅOÝ Ã‡ûf¿dÿÓ]é8­Ó£€£©'—«›HÁCá_•Çp¥KùkÍšót¯(Å$Í‹˜+ñ¹_Ï\µ}–‡|Ï|ÓQÝ¢ýcýIû¹*¥hÝ€‹qͧ¡ ³Ï°—,µ`ó5›”Ñ[¹¥™3¿sÃé$›±¤ëN©C³i—1»^÷;‰ß,éJÅAáÙhÿ%õ Ï ÉLé„Ùåu¯)Ù`§ÁrÁe¿Ó£ýÓµ/¹i¡T±Cå+‘Y;³¥¥_“šÓ×dŸNÿm× õ0ƒ0›|v¿šé­×H» ×EÑ;í„×Jí¦L‡XÍ|ë¯2™ró;ïg¡‚ƒgûÍË8¹‡í¢Ã)½S“íe¹:ÁníUùOµ·Ÿ¥`‡#ý–í!Ë¡‘jëdÏ6ÁÇ>lÉ&ßÓN§›Å Û×gÍxÏ‹ï}Ù‘­«±žË0Ï·±ÝT‰²çvï<უ8áYÙ;ãká)¥…•¥mÕ§÷ñgÝgÕ³§–«~«‘ Ï›ÛFɧ7ñ;™ÿ£ËŽÃq§…ã]³%«±ÿsÝw¿xßõ€½¿/Û•Ï£'Ý‹³Á‘ÿÕ)Ý’ßX§-ǯ“±œ¹¯ÿ½`£Iñ¿­!«™zÉ£ûbs¯,·’å=É3óV§‡±+ŸŽÕ ÅráB(×®É"×>»ëµ‹„Õ;÷q‡PñRƒÓIóh~ùG¯i·l“£ÇÑ„óvÿ5ãR¥õ,ƒ¬ÕIï2Ñ:—?ÅRÉG‘5Ý£—;ùX¡„‘±M‘ÃI¯fÿc‰ý+¿Aå©›LÝ2ËC¡^ñ·§ý›ù ÝWÇ*µ³ÃnçdÁ/™£¿‚¬óaÉu/…Q…•ébß™p™­§3t×±ŽÃV¿¯õå1±hµ±Gõdï¬Ë?­« ïz™‘ÛHû/Û·L•–ùžõ¬›U…‘»~¥fã¤ûm‡,ßq© ­‚•ƒÇ$÷²‰IÃ0™TµSóWÏOX±±¯©? 霓)¨÷XŸ„¥,÷ÅqÅW÷!ç+é.—6ÑÃz¨Ï8‰‡GÁ$©)»ž!ën›o¡M©@­ªÃ¥¹³÷¥‡u©fß-Ñ®ë|‹e£=›yŸ$›µ0ŸÙ!£}½t‘¨»ïNÙ›Wï/ñªñ¥¬‰O©r·k“û‘¤§aÓ«³:±š»Š·‰}§F‰‚¡N‹lác±Ÿ÷-¥ß™§:§¤›xýjç}éÝPƒ€•RÛv¥®ÇP«Xád«H«Á¤ËVÏ_‘1ëG§2©_÷J™@ãˆ÷¿“×ûW7…§\ß:É ¿uÍ.ñ¥é•!ý$ÏL±Hߨï¢­aç4Ácó¡Ùw¹ý£™k¿_õƒ›)ëŽà «©ã“µ¤¹N·­¹ókç<í’£™©«ñ*Í&ÃáƒOÍ<›V§x“žÓn…y…Ž¹>ª›‹œ¹ ïq“Oç¨Û­‘¯Ë@õ é©£Å!ÑE§6ù*Ù#‘7ÁLÛ7†)ÿ_Ã?•©­*ï -™š§ó¨‡…»LÝB±¦­’›“©ë -å -Ѭý#ÝϘ݈ɤ§Ÿ[ÁšµsãKŸ‡§^›Û*Ù»Fñ8Í¢Å/é¥ï?Ñ8߯x³A×8Õ€½X‘+½”«¬áPÁg§r¹)ƒ÷7÷O‹$Ý•€“¨›#¥«ÉN•EÓˆ¡õ[õ`Ë=ã&ÉŽ©Dë©¡ëaí«ËÑ@—¥ñ'ï|ÕŸ«›cË*Ã…Ÿ–‰^ßZÛD½sßt¥†¿7ã‰í\ÏNù©· çëá£×RíBå ·Tã­nŸcÛP×_Ù…û¢Ÿ-ÿBõ{é*ïÙ¿>Ƀ¤É«Í~r…uŸã8ßV³‘©ªHÛ/é²½©‡)õíHñ›‘ûOíq»‘»"ç5—=™R÷ÿÉQÍb·;ÏñÿháŠÍXÝ ›!±V÷aµ—£˜בç·ßÕ?¥Hx׊ÝŠLJ½…µƒ û–ÿA…H¯¨ë¥:çNÕ…­¨á„¹‰‘:ïýa㟗}…<‰s‘G»‰ó7ïªÝ™µzëC£ž«2å8Û$ÁÓ‘°Õ9ϱƒ`¯8¹›ñ®áHÑ‹—/‡?ƒ›í;…Ÿ ‹.—pÑdÏ3Ã.ùUÙIÕx×bǧ±/‹pý¡“f•Éùg³ßMû@ť˗‰¡¥—`•q­<™tÙ.¯ ¹zŸk‡œÕó«‹fÏ©©péX»nõ;‰Šå”ë0åm¯§É^ï—±Á"×ß=â½uG©¤ûr«ZùtÓ-³[Íå ÑÓb‰PÓ8Õ£Gµ‡û›™“‘Š›œë¦³oí©ë ƒK¡sóƒIŸ=í†ûÓ°Û(ÝA¿&¹¨Ë Ÿ"¯:Ù‹Ñ£‡¤™›“yƒ{­³­Tñ¯‚ņ¹=©·=­±ñL§>Û§‰u³¬‡'Ÿ=©Aó»••Gáb¥Áxµµ(› -³D±]q$§N‘(ëŸ;ÃãzÓ Å7Á¡³ãp™„“µ·ŠÅ óG6ÏwõBÝ.Ͻ#@› Å©z…~­&ã½Q­‹¯mËZÙq¿¦Í8…‡ŽÅYá^‰”Ñ•‘6£ý¦Å• õ:ß)ƒZÉ…»B¿–ý«Ù‡Í€ý;ƒ³…í ƒb­mÕשÛ…ó …»…‰wÝ6ÁEÉ\Ã¥0Ë…t±(·z÷šÃ©3¿[Ÿ‡¿†Ù‰šÝ4ߣ¡x×@¡Ë¥ï…çšï±fíÛ,³ë#Éh³F“6ŸXß ½ró•Í^ƒ^©mçs·Žçí a£sµÇ­¹»9ñ¡‡`õÓý1åPõg¯Q©X·|ã’ë6·8ÿël•šÁ»C·7ç{Ã{Ÿn*—¢û»!ÇOÿƒŸs§¯ë%í3Ç]Û|‡ë­š•£ÍÃiÏAáínë<ÃrëP“l¡&§hÍžçRß/å“¡F·¤—E¹ýMñS½B¡v“—ã‹hÉ6±¥¹.ßó…¯=í)Ϥ§;å›ÓUÝ0ÙS×»e½&íz§—‚ÿ@Ë -£Ní‡|¯]ñW‰¿»qóû=Ç÷|ý‹÷±!ËÏ]ë™……ÇM‰¤ƒeû-ý¯±á5»RÀï ‘ ‰…“Ãœ§t»0Õeå/™<¯¡·ª•VÁ ɳÿLå¬Çt¡°ýDµ·bí(çQí ± -ËH—+½wó—Ù²íÍfÕ£§ ¿—Ñœù‰ã—ÑZµ­3Í*Ñ…¯”ñM¡]Ÿa¡Ãe“¤±Oÿ‰¹‚‹J¯²± å«ï9ƒCÕO¡­Ã]«1,ƒ:ËÓg¹r¿1÷nó…‚ó «ráqßJr¯‘½$áˆÑ|åÇÿR‡ù!ß²ù]‰–‹<•Û”‘>“^õiÍŒÏ ï^űw«-—8×­£µqç‹û)奷c·h›¡ó!ÃY÷(‹®µ ‹*‡{õIñ‡w¥°Ã‰§¡‡ûXµ•ïñD…©¥¯–í Ï~¹+Ù”õ¯Õ­™£%ÓD‘’û£û†ÿ|­®£®«Ÿµ«Õ“ù(ɃßÓ«3­Œ¹ ‹zùpÛq½½lçSbÏå5÷«|«ƒ«kᯜ粧™ù™=õ¤§‘«'û(ÃOÝ$ƒ£½6¹bý*‘ ¯©§sõ£nÕF•¯›Ÿág¿*ƒ‡Œ½<›dçBÏÕEÑ0礡#Õ<͉¯ çwíŸÍ?Õ¡É©íKÉ• -íjÇ}Ũ¿w“°Í[áRÓW¹GµQ§¦¯µM¹WÓ3å3¯¯ýNÑ%™P±EãŒ$¯4›2—Ëa‡²åƒ—o¯c©”Ó«¤»3ý—߃ÏQÁoŃ«!ã2ûªÏ2±,Å¥8•vÉf“E‡€ÝEéBá ©LÁO»–ùhÏ0ÃE¥›`¹S«šÛN ËquÍ›Ãí&ͪÅ\½‘‰ñv•nÙ7¡yÁ6å—Ù£pŸ“v±káŽÓ.Û;°é9ù_‰_«uûš‘”•¥oáM“¥¯‹“ÉZ‡‚©|ã5³}µaÍùˆƒGÿ2µpÍ­ó·ó õï‰@ïdá -ÝFÙ±B™—“&ߢ•M÷‚¯q·‰W<ƒ•»4Å í¥µc™cÏ–së”×qƒù£b±…‘³õå~‘—ÿx‘M£ƒáS­A\ -çmßIÑbÅ-™5wÑ<©§ï²Õd¿6ÙQyÑ¥AÁ85Ÿ39Ù%+ÁA»4‹?é?9·[Õ‰å¯8)éE½ã,í3Ó Å½ë!i•9‘b5©7ÛSÃ>ÉÍ-õ/‡®½Oá­M1×8Q;ó%™:‹‹8Ýõ"ë9· -ù8×*é,»A±*‹ -¯Rí —$ß9›5ß -ó0Óá‘GÍ<Ñ£:Ã4û!Å:‹0Ñ ·4Ç(«"‰0ýƒ§ ÝJ›"‰4›#™"•Û5¹1ÛŸßa±!Ïã­ÃP¯,¿A· Ç9£ïBé0Ñ6Û0ù!ûŸ*Ñ+ë6§<ã‰B‘ óO¯çB­­!£©')t)T-Õ`-»9ñ‘7é<·“$Å -»~…ÿ ‹‘£YÉgË$Ár²•³«Z÷ƒJß Ÿ<ï‡ß2½ -í‰ÿ4‘JóeÙ4Ý-å@Ïfõ,ÝN©ÇÉ;ë:ï`¹pù(©z±ã§±BÍ~§Jµ\M‘\ã×|ƒñ¿ÝEç.• × Ó_Õ?ƒ%›‘TÙ½€ó„Øñ=‘ŠïqçI猓‹DA·2‡LÃë!¥6A§©ÃíBG©A‰ GÅïó ¿ÙHç)µCñÍùç(oï·¹»MÙ!³Û©0·Feñé)»;×8uõ+aÅ -§6¹*§÷+‘“ñ8û÷aÝU¡Ógí©aÍ0ÿ$ý"¿!]ïDq‹r•å8ßZ9÷6á ûF…Y×—5§[Éÿ.§—#«ÿµ?é-O!¡%Ï*¯ÿ%‹nÅ -cÝ‹Pç!C掠*ï!ó")ëÓN¹ký­( -µ ýO™+‘FmÑ6£‹,W¿A“#Á“cÃ!ë`ç¿$½AKó*%——7;íAÅÁ+Ó5Ý7sk·D­Q剋rwó “¡oë!•ƒ4—ÇMß6× ·³ åå2ÅP¡'• -á6IóF½y!õ%‘;…2£¯!¡"Ÿ¥ƒõQÉ ÿïl«Ë ¯4Õ7YÏ)³.± ‡3ýû_ŸA³9›(»"Yµ>Ù‡qi¥ó ½‡#ç¯A‰,­Xk· ™7ß%Ó#éOÕ ßŸëí&›J³ó:³§!:±#uÛ7Ç9·e·Å.Ç6«"Ç¡Á ó`ß~›?5›QÇÑ=óã#'õd±2+§c‹#7ÃÇ6Õpá!Aõ%­A7ŸW!§+WU± §^‹"‹:U/‹ñ0¹?µ;‰=;µ NÃ+eÑ ¡7ƒVWÍÝ8ÃEe™Õ!¡®Á“‘9¿˜¯ûÝP»‹‹rõUÕI£#ùk›¹Ý8ñ»gÍ -­m¿/› ¿„ƒÏR—l³™÷"¯‰TŸŒÿbÛ^ËvÕ ‰vå%‡›!¥)…Eç"›Ùxç3Á Ñ‚Ÿa¡£")ñ Ãç#õç7ÓP‹.ûy÷+ûlá¿£ É ùcÕ•AÅC¹2Ï(ñ¥ É"Ó#ù2» Å¥ª¡Žï!‹Û›•aÝ £PÃ?™ å4‡ -Ãï$‡ ‡#ù -û3<§‚£3:ó8U›h¡ ‡“ VÍ[µL,»6÷RåÕìã σ Çi“AÇ+áã(qË…ï’½ý%lj#¯cë“7˳>¹•õ5›ÕN¯ÇU‰i÷ß}ÑžÉ:Ã?› -éãÿUÉžmÇE-Ï »)Û.ñß‘8 -;‘(»I­8ë£U6‘Ù#ñN»Y“½ 3­89ùÿëÇ0ÓIãŽà É9×(Ù0±TÇËÛ -ÝQ1 -µ‰‰ ©íǦÇo3™ õó4©?í%ïX½­#ã‹õu£fÍÓ/Á«"Ýé„φ· -í$å|`/©¯»#U‰%é‚«*C‡)‘«+ý )ó í^¿!—Oï’Í?Ù$Ë¡’‡ —7™{‹8ÓÙ «^×KË— Õ$áy7© -å.•cŸ7ów“¿K³0Ó íl'Ï -ËX)©!é*ë{é¥ób9'åZÿïÅ!ù.Ÿ"ÁC× ‰Ç ÏF» ç…ÅG¥7™i¡ ÓŸš§ »;¿ ™3õ «}Ï! ù8‡xÛ7§A¹ Ó\¥ ûxÙ8ñ!—z¿‘¯9ã“9™s‘"—˜ù ç·E×.³7£¥B³[Í7“|í!ɹµ ÿE¿5ï5!×=ýݯ8ƒßyÉ¥‘Í›#íO¡!µ™&½í7¹GM•6·V…!£Pùû Ã$­bë1ãXù“÷?×çÅ.‰ûÃQƒÃé#½&ý#¡ §6Ï­Ù"õã»6Ù]ãÓgÑ"áýX‡S÷;»óPã$£?‡ ·0á7Ç>­(á/Õ9óZÏ+óÕ!É›[É&ù ³<› ëƒÙa»R«íKÅ0Ïçcç‰!g‚±™$_Á"Ç<é åÝ ÷b±HƒÝxûÓO• -ù\•"ÃýŽÇ !»6ñ˜ÍCß¹½Z™Ëgç£ ßï“)íP‘ÿ™!ùµ ‰*ùJ—.Õ ·(£ÿ›/÷J±ýi• « í!é6§ûá$Ó(ë%«*ÛKå÷:µ—$¹<ý%ÿ«0á ¹Å‘× ×+± Ã*ËHÁág‰#ÝÅùK« ÿà ¯{§¥ÍÉgËïN£ßó%ÕTç ¥#Ù -m£Uà -«*Ýn½ E…4ß%—Ù:Ñe“ ƒ:»å »$¯N±¡,‡B'ýŸ"»‹9ý"Íåó••¥ïí)¿Bû¡;¥ !Û‰J7<ƒ¹ëùý{é ËkùÉ@áÍF×M…¹½#•ïY͇Ká.C¿"£ë:“,Ã##·ñ5Á•çû7‰'û%Û‘M‘3‡4§”ÝV—;Ñ™ûIõ(ñ#ű5‰Nµ å.÷'óY¥9…V™ -áN¯3ÙN‹?ÕMÑ%·BÉÁ@ÁÅu¡.·ã"©`¥=ó ãßE£.Ç -Ÿ‘E§ ÏÁ2épó…pÕžÛí Ù›háë>Ó<Ùï1ç7¡Q¡óƒ¿«é‘aƒ­Põ-ÿ¥á?à -›ï[󚧟T™Ãù}Ç%8×Ý ¥Ï)·9Û:ótËýÕh·k£ßÛƒ…=Ï3‰•Á««ùŸ"» ­7ï*Á é*ó5—“ƒ™ËOåùõÛÑAÝ%§ÍGï#¯ÿ ç ¿9¡(é á(ï Ã9©‰Á ‡ Õ>é#­.ÝŸ7ϯ Ý8ã­ã½NÉÁ Ÿ'•å"ƒÙé«9å×`¯‡’õ¿ -á5— -¿1÷© í6ã% § ±M‹‡í"¿ õ/Ÿ û™Oßåë$™Ç6»Å1©¯"ý•…›#ã±&±…2õý ßÙ#Å!Ï#(¥µ#•(×"­"×õ— ƒ&ÿ»Hñ ï³7»ë$Ù éÃ#©Ë!£ Í9­2™ ñ ‰(›#ÇD×,¡#½½¥ «#•Ï"Ù-Õÿ ƒ¿0û ÷±"ƒ(±4‘ó.«9Ýí9ûÍ%Ë0ïÓ!—Û_µ?»K‹™]û1çwÉ—¢YÕ«bÃJ­˜É³ƒTí¡ƒnÁ³—ý -hk•rï!ÁX5ƒgÍIãÿtÃ(¿…‹™!Ý4™*{eï8ëå0¥Të£-ó0Ññà ×ûaé&½é3×ß‹¡a÷…-Ë(åV“U ³17õ*“&ÝÑ/ç>ã"Ñ÷ˆÉá׃Xû™¹,í£%ë!§•1÷P…ù½bÃ(ç Ç8ÝÝ1Ç«,¥"¹0·QÍ-Ï ‡4Ý «1åµ+à ó·ëCÅ ­0…Å=×»6•’‘2»6í"×#ÝPÁ_™éDý/·66Ë -Ù-…í»~Ù ¡å“ Éb¹­_Ý1å÷ íW•&é óEÉ:ë(ë“#áëJá Ý"ù'ù/Ï»&³*Ý)á ‡ ÷(Ç áEÑ3ƒrÍ××]Ź…z»‘·må!í»!ÿ÷c•}å<ƒ\û ¥WÁ —»§ó1ÏK½=ÓÙ1“… ï(·é"•í§1ïJÁMñ$¹ß%…OÅãÑÇB›“Á˯ù=ƒ«hû’“Vçùs«kß#ëp¹/­¨£Bá—Õ‹ŸX›2ûKÁ4ã1«CåGÅFÍÇß‹;ÿ?ÅAó»ë9]ÑGÍ%ù3áÃÁ"½:ù;¹ ׫:± (Ãý å#åT±"×å™NçÃÇ£<Û­™Ý"Ïaÿß)˹ »8ŸÇƒ›ã'õ Ë6¹§Ç ù+Å'ïù(³ Å÷"Çm‹L÷9çï -õ!Ý=±ë©WÓTVŸXÇDé@2çß!»+ûã"í$ÙKÙ…tñ³Ñ:­$ñ<å=Ý5•)£"óÉ+©óÝAÉ6­>·¯ãEŸKχ ¥µs3Ázã½ãcý/ƒ ‹ é:£:á'• “2¿ -ë08»Ý}¹!©­jË&ùåD…« ¡]…~÷§ íJÑ#±*íf±÷5ÿ\¿ -é4—D‰/¥PÉáÁ:ß?×ñmG» ù§"Ë%á,§-•FÙý$?¿•Û8Õb½8ƒç-•P• ½6‘å5á5½:ñ Í!/ƒo½±Å|§ˆÇ2í6×3CíñDG£6í7©.ç 1…Rýç éLá.Û …8Åq7Åå8³ ÏÝ4×Ý8勵©b­Ù@·K™ÑA©Wó·’×#/£—>ó"ã£/µ7‡› -#ÇE¿+±™ ¯­?­1ÑÇKñ ×6Ëù"Õ¡qQ%¡t¹¤õ‰U­:Å-‘>ÿñaÓšýˆߢá&+ó­…§ -õÛÑ•‹ÕŸ%ù£oé)ÏAÍAã !Ù1µ@ÕMÇß«&ù¹@ñ>9ë ÷%/¥O@#¿3·<‹A‹%/¹r-á-CÍ[ý)ór›×2ë>©ÿ.ãÍDç(§¡Ó&#ÛE·3Á[‡:Ù,«­é7Ë«7•«:±Gñ8û{“"ï¡:û=ó•%íŸG‘8á ©7… ï¥E»?¹<¡6£4Ù%ã#£ ß8å ±!›xÝ%ÇyßïRç©H­J§Ÿ‰NÁ•Ï ‹Û¡0¹ -·Hû¯çOc£ß…Lß!ÿ# -›•É4õ8Õ=Ý -éÑ!áý£F©»)ëÕ5Í7“šñv¿Ëa<ýY·¡‡¦¯<­Ã'³‰¡XÉ'“wçÑ’Ç›¥V×…£%¥¡‰õ.³nÝ©¡©ÿ)iÑ;• ½»8õ×l‹3ÕLÃSã"&Ã@¡nÛ›c“1¥­z«(£CS¥>»0DQ½]Ÿ マ]áa¥3·UŸqï—@íhË¡n­ Ó"épiÑÁ!Ã)BÃ~iÍÿoS¹AÙëA§µ×GIŸÇíAéS‰–±áAÍ)±vïáeQ·G±#Çï@ËEKûó^Qõ=Ãa•|ë>o±C‰Y‡8“u—n¹+£{ÍmQ›PÍ ówÏ­!™9™³?[Ï7ÙNç}!‰o·LŸ?Á.­O±ëE‰‰WŸ £y_±3ÿ7ÁŸël×F÷_Eá#ûVÅDQÑ*‡eÝ,±Ë™0ï!¹2kSûEW¹X¡ -½Lw›D¯9¡La—>å@S»6ßl鯧|õkµn×"…!Í… ©“·‘ƒ ÷õž•› ‹$ëoëm×7—#ÇQË”©ƒ›[íQ­Çá -ù󧡫ƒMÇÛ(±[µfZ‘-¡Vé\«©ŽÓ‹x©(‰™ŸJû7ƒŽÕÁÙƒ¿±±©³zËRt׃ë=‰P»LïÙ\Á=Ëý—&›ý8­7· ‹dÓŠÿW•#÷¹ í.ŸP‡­“ Ý ù`ï Åë?÷™É¿ãKù"Õ>…„¡ï -™<Ï"ÕE¿$¿YÅÏE££ç6#µýÉ7ÇÝ+ñõPé É Ñ#×­5“ó­¥p‡Fá=ƒÓ*Ý|‰(½tùåÕhÃéý>û ¥, µAó™Qß!§¡a¥4Ñ -éP± ùß&ñ%‰­pù·•»Ÿ/»· -‹á ×GÛ Û‰H‡VwÙ#· ßF“Ÿõ°¡Cƒ *­7©>ó9© Í%ƒ™"ש"ÍB¡™q½9—]¡"ßÏ›oÙ7‘¿$ÉX…¬åÏã«v±» Ã#³_Ù ‹½4ùqÇ0ï ­¯‹!§ÇÝlƒ„ÉB|Á(Íxõ4…"¯3Õ3û¡Õ„ñ—V•B­[•'Qã!ùJ­+åb¿(ŸP—ûfÕÕ„4ýuñMù5‹~ÁRû4ÛX6=‡”ÉÝP‡½\ï­Wí,Q½·\ÁÉxÕYÉQÁJûJÇ•… -Ía¡ •^¿&³Ç)ßV¹;ûLÙ3•a…(ùõѹ$É,éAÃ:Í …@ŸC· ‡#™ -­ë±ÿ«¡ª³õ6ó:צŒ‹ —u…\¿H-áÑyŸ*¥nå·oÿ&Ûу“žÙŒÉ Ó«ï²Ùž.ß|ÇŸõù¦­^㘃C« ͤ?¿@7Ý'ÁÓý寿¢ÏhÙ(‰ËátÓ‚‘­ -ƒÑQÙA»— …€Ã%ût¯ í4«i‰Lù½ŸQóa¡†ÛªÙKõP¡@ÅmÁ‘Tá•*ÍOÏAãÛ]›û'•$ï ÅJßh½ ƒ\—7Ç/÷aµËŠË…h‘Qù8É­>¡IéE™© ïVçë$ÁKÑË«÷@¥Uñ: -™Ha³vù7ÃM×`éÍa©ùMÅHå>rå[õµ É;³`÷ŽË¥‹Ï6ádß&Á¯…í"·Ï<—李 ¥ ƒ?U§%»!¡É9«5aí¡í!£e‘Aáï·#±£ -·ÿ*·I_Ÿ:ÿÉ`ùg³¡ýJ‹”›>Ù›q¡BÏŠQ‰ï Û~¡DÅ4…ÁTÓXË„ÕtÉ> -ãz·÷Vɤ×^£@ÛBñx«D±‚Íp‹§ÿ­Ëmµ*Ǭé -£ÿJÕ«`­ýšÍ–%Ÿ_¯Í.ñ›Ÿ§ÙX‹g/›ÿ4…SÙ Ç!ûZË&ÓïW­ ëTå Ñm©áY·>ƒx¨›5óžÍ1ù„S“†ÃÝ™r³“•‘Ë?ÿ屩d¡ Ç™Ïiý•©D­—>á@”ÉwÉù3¯ ë!×Í#ý*ý0ƒ"‘«;µñUÑNÍ=•ß Å/í» ÙA£ ÝZå*éÙ -ß‘ -à -ñlÇÉ,û9Ù'¯•@ËgÝŽÑ]‰JM³Qcóß ·Ó§{ûs³Ó:ç!±É¿c¥.ë3ù7Sï8‡•b·™ ûårá ý -µ¥níÇËÅFéÿ*ŸÅ+tõ“#“Ó ¥8í“-ç~¥¡é ±³}õ­ת‰—“eO—·óÓÙñ£÷"õ;¹³·£™ñ‡sÿ'Á`•Çƒ™cå\DÕšÅ&ãAù<ÅIû§—&µÁ6‰jã•uû:Ç'ó¢é#±F«{Ë®™צÍD=Ó`Ýy“C—2©Ñ »lá -½3›dÙ§ýQ‡.ƒ¥±oí¹ …©¡Qà ý|» ¥Bµ ÇLÿ Å· -õ—ÿ,ÁÉ ™wÙ -qãåE“)çn—Tµ¡0½@…z³ŸbËC— ¥?•q¯ˆ±xÑ…³Ë~ѯa­?ÝI»m¥"«]×DÿaÍû•HK‘8©P‹4Á8Å@™ ÍŠÑ–™“6—OÇcó‹8“.«ÕOÝdÃçëF›ÝÛ™D¥8½iõ ½p·!±@Ñšû›sÍ&í€Ó ó"žé…ñ®½9á†Í·‘¯«Õ ßn‰ -‡¹Ný¡¢å#÷ˆ*í[óUŸ)ŸF÷l¿Ž—í¥‹=¯ “jé!·W¡pÝYסÍgŸ4ñf¯ñIÁ5ÿÉ_ù÷•» W‹’«)¢± ™—¥{Å…áV±qã•£Dû$Ña‘ ×$•‰“ˆƒ&Û”‡‚½¤ÓFçDý˜ãF“Ã,ÛÝ\™¥§‘g“2Z÷ ×{¡“F÷*§%½‡×(cï ýA­>ý&ç‰fÃï?—?Õ@§(áC¹TÑß0§'ßDÑ(¯*‘‡f¡xÑ%ëjû¹…xÛ(ó©@ñ-ÅM©©Ç'‡ךчj™Û{—¯ÕNÑÑ7¡ ³Bý7ç÷™§ ý_ÍQç’õ-/Ÿ © “:å «~ó í’׋#÷¬ÅrÍ£¨‡5…3ûe‹%׳ ‡^©;•{¡Ÿ…©«³›“ ›„5¯»s¯@§SÕ+ƒ/ч­a›DÕx‰¤¯ ƒo¹=¥“Ýn©¯4±Õ¨Í9©hà Yƒ5É¥†Û©û×r‹aëÙÙσ`‡³³ï÷k¯#½§Ï ÃN“ -ÿLÙÃËálÍ©O¯Ÿ‘$™d‘¬…q‹9¹]ã6£o‘–ù‰)õ Á@ã -áIí=É=ù »çÛÙoç ›¡qÓ!ŸÅ!Ón±où9«8%Q+ñE9µ#ñ ˃C!Õ“ Û%Ó+‘#•&ƒãR¹ -‰<75«Dç'›$Ó+Ù@¿0‰ ù?q‘½"ÿ‹ ñå ½(§E7©·!í0Ç@%ÿ­M'ãñ0í3Û#ñ ¥(ÏëJ=‘9½ ùe›“ å±MŸ -§W•#‰á'£KÍ­@«3¥é;›A³ µL·0¯ ¿ùgýÃ2Ÿ?ù!»5¥Aù×+‘Që» ÇWù×T©"Õ‘)Õ—8Í ë"÷D‘4•?Ù!Ñ ÛJù/Û×ßD¿Ÿ‘…íTˇ!‰(Å%Ï`ýÝ ¯»h¹(ó‰ à -™ßR³ ßùí)Ñ­9— —»§.…"é=Ù-“#¯Ë í,—M»é ‰C%¥Õ ½*­!Û÷<½ »+ù"ï§8É0¹—¡%…ù<›ÕL¿§9›í&/í$Å6ë<¥ -­Lß*Ý­5¡!÷ï8Ÿ Á)ÃÑ+³ ›&‡ã:!Í@ó‰#ë!—@í‹%µ -ÿù"­ÉÑQŸ^áÅ4×ã¥uå¡Ñ×<‹5s·á§g»mË(©ÏR¯[ϘÕeÁEOƒý`¥4eÉ?Ý#· a÷C‰”Õ'§\Çc‘~Ù‘RÇ>ƒß/õ&ÿg‰‹õAI£ñb—ªÓ%[õ>Õ:½G×›ÿ4ý<íi¥½aé -E“½xûcíŠÏ uŸB¥VËV颓5#ãx›²½ ñ…m‰Ç^“· oÉ@Ñ…—@;¯±5E?¡;&íxűÓBÏE­!§;½¯­g¡*¯yß+»Cm£™7÷£DÑ ¿B;Á:©ë"Ï ³ƒP«'•±RÃe»=ÛÝ@ŸPËjÝe¡ÿkƒdÝT áõ>ãR¡±Ó6Ó5_§ …>ËT©I‘7»WÏ¡lí » Ÿ“é0é8W§#M‰XÓe­D‡1D¯ÿvÙÝ“ç›óo—?ù ín§ÿn?· ÇA™GÏAËA¡ß!ïA±Q…No½V½VÝ=ß4U9åaëz™kóµ8R•Ï'› -Õñå‡Ñ -ñYÅñ"Õ*½0¹@¯¿ AÝIË:ÉÓ4…¯"×¹õ £û=¹0Ý£7Ÿ¡S—‹Á“ÙhëÍ/å2û>¹)ÉÅõ+Í?¥Ý&µ—¹ÿ¯‘+»¿éb±³)¹‰ ¥Ñ‘(í¹.ù:™Ñé _‘Õƒ‹aãÉ ÁùZ‘Ç«8—)÷ý­ÓÅ Ã&Õ×ɃßUÙÉGýÕßåý×)ßZ«ÇÇ,©:—ó‹ß6Ý1Çeá™)Ûf½)­éb«³1»÷ÿK¯Û)ËûDËÙ&ÙF™'³ ­Ï‡«`÷é4“ùl_ùYÍ“sᇃ -—NW‡å ³ ñ•Zƒû+‰ƒ —]·5Çדåû瘿˅ù•QåQ ƒí'‹0‹‰D¯ŠËN¹½¥ -£Ù½n•ÃãóíY¯§ -ÿ%…#¥*å'×0õ#‘ë… ½÷·±×.³ ¿9;Ë?§Åóß?»CçÙñ:ñ¿Õ¿0Ÿ+¹½ë«8Ù¯$«×@ý­„÷áÛIû¥Íbý Ç1ŸOáÁç:áH—‡JуíïÙKµ'«¯‡G•Ù÷ó¡Û§?±EÁ¯ï åIãÕ!³ …\ɲû±¥,“Eë˜Ç;Ï·#÷ÛaíX³±*‰Ù#åKó -ÁwÅ9µ=óÃBÙ¡­W›ù9õI½#ËBÙS«ý•m±$çÑ"“&û;ýµ³!£¹©Í\ í!ßïT·FÃË -¹³TÃ&ý:åÉÍ6½ …a#ë'õ» ·Çë•ÕEÏ-±± ë û9¡(ʼn‘S© ÙÓ)íkó­"“?—1Ù(ÙÇC'á"·6Õ9Ÿ"•0á ù"=—£#Ã¥‡@Ý(ûoi ¡d‘ £ù‹§1ë?7«©‰K™ áK§‰=…™ ¿I™_¯û%“©8ñÑO™Áx± ó.‡a§!£m2×NÇdÝLÑ›³kÅ­2ñ,×`ñNÛÃ’٠ݥg‘{£Re‘Z÷O—ÓNEñÏ>ë™Ã³7ËÃg‘ã/ñ6ǻݞ¿³¿^å Ùba›9‘ …§ ïUáë’Ýã/ñ™ëy£Ñ…{û 1‡7Û£:«ù¨Á+ƒ ßšµ -•=ƒ#Á~É͉ۋ·íW« ÑŸ ó e‹ ¹9Í(¡cù;ÙMƒ ÿZÁ%•Õ’‘B‘ ÷€"Õ£7ÓÇ’“1ó6i•#½ ‹ çù;¥4¥M»˜± ᘷ é÷…u·4û©Ùvé5ûõ“Eñ8™˜× -Ï~‰'ÝH¹7í -Ÿ—!ó‘½2ùL³\áUÛ˜³ ߇ »r£7õ0å8Ë8ÙLÓÓ’¹Sùÿj›#¡lï ¥jÙ3Å(§n½cÕLÝ!Å-¡8Ë3ÑŸ}÷4¡Õï §a¿ï•¥t¹4‘#…ñ]Õ²µ{Û…}5óÛ ëí>ÇÓM½k£Ë‹›4×c¯±@í²é[‘7Å -?×ZÑZŸÛOõ?í ƒ%Ë¡4ï_I¡P·;±‹,›¥8Õ S7ÿí#»!ßiã$“[ë--ƒ*¯"¡±é$…A»Í6·7ÙJ]‡‹§Dá7õUÑJc³$Ï“>©¡ ¯8·ÿm)Ù90ç¡8›µ!‡ a©p÷ ¹$[ùl±]¯AéAù›eû#—Y¯9Á ­Û6ïAñiŸç[ñ· ¹q—Ÿ5ÁDûÙ"Å#·"¥qý|o³ c¯ñwÉaÁ…»,«tŸDûù9é7ƒn‹8‰CÏWß6ÛéSÓ±6WÅ¿S©9åbû ûSÓ?émD™/[»LÅ!£`û&ï·1ß(«2‘ Ïõó!“Q£!ÏIíbñûZÇ8ÛJ×9Ñfý1§0›&©·¤ùyÉ7G‹ ¹[¡ ß -ã g÷%›A© ݹ}÷(¹bïc«!ç;‡ÿ!Ã"ƒ°§§zg‹N×a»Á!½¥Ó ¥‰§ •§ ½‘«™aµ—µ7ù–£ÇbÁe·e… •#§"Áû?± -·5gÕ§J‰ÇÍ µJåA]³ó#ñtÓç!×wñ­ Ï9cÓ§©#·{_…moûU™ -M«“nÕlË_Sù$á;í+íx/µ‹_‡ ›£0uQï!…/û8Oã(Ç?W×$‘©ÏnÓWõÕ‡Í|Ã-™@Ë -Ý6kϽ9•/— Çv‘[ió?Ñ,¹n͈¹Ù¢Ù‘sËá ·]“‰Ý¹fiá Í8ï”ñ/ÍW“Ë ‰¢ƒ9qÅ!ß!çi¥ QùÉ#S• -É7±PÑ(·§±ƒ É»Bá8i¡ ù•·R±S­Ùmƒ —1a‹ -ï8\Áž‰ ¹…ý ‡k5‰%Ý/J• —cáBñ ã:ƒù6©£nå£ —ß#WŸmù'ÕÃç‘Ïÿ« ß’ßw£a×#á ýq¡½¹Œ­%Ý!ÑQk©²«f#Y«Kɨ·’ͱ‹i…gû£#‘ƒ É.•å•xï-é.‡­Í$³,e­÷¯§5¿0‰¯÷¢ÇÓ‡Ÿ8ã Ï ‘Å·9¥o¿°‹™‡ï7VÁÛ×7 ÷jݳ8µ ×™B›-K«LÇWå ¡Uã!™’ï -”+ï{Så;õj‡UÏ ]קƒ]…[ÍÓ6Í -Å]Ÿ[mÃ9å›l›,• m÷‡ï,õ— oaïg÷m‹×ë¥D‡DÓWŸŽÙj‘cåñõ -Ç“µó|åOÑ„ñƒMçvù2Ãé%_‘£6Ç=ß—9ß3ƒÇt¯j£Ã¥ùc¿JÛW÷žƒ‚ÿrAµ#½-٠é Ç8¡"Ï w½mé^±!Å¡™'ç£6û½„÷œû…Å oÙË¡"õS‘F©2ãÑ"kë¡’ƒy­;ó!—#K¡5Ùï#?×m¹Qá¯"¯ õ8“ Ÿ;Û`»5ó ]©Õ -M­[‘ù!û%kß7‰N©/Sÿ•«£Û‘ÉcßFK‡ ‰£˜e»{aƒA“]“©7õ…¯®Å—£Uá-džÍ«¯1¡Y½”TŸ;¹‹÷!µŸ…b³7… W…f¡ Õtcƒ ¯gÃ|¿ñï -Û ÷½&Åm_»¢Ÿ ‘lÍ!Ÿd“Z™¹?™ Ñ­ ÿq_™aÃ"çz½Û@³»6‰¡µ­“FÃ!‹ ý»°óhÝ û:]‹…« á3é:_·ƒíLד$U› ¯iû"ŸmûÓ©zUÝqÛFÕD­‰ñ -•©ûë »‡QËg™#¯"Ç)Go›#›’Ë#·"¯Œ(ƒ a½wßYë™Ùsã>½<óƒ"ï“Í6Ï;ãEU¡8« mÏ•‘½só@¿8_—‹÷š+“\k·Y·AéO÷¤»yý8QÁùyýA“7ÿ›±$}ÛÃA¹£q«ç Ù« ¹/Ç™<ÁÛ ³'±ïrý£¿™MÓÅ 1g·ß¯$±NÿŸ$¡­jÙ0ýùÃ,‡"éñ9× Ç÷“Åõ ëRõó45‘É í“ÿýCÃ6M—ËóD·"¹­ +¡› é ÿ:“«4¯lÃ1ÿŸïn‘Ãm¿7½/Ánõ–•»Oəǧ‰²¥(é|é—=ÿ!Ë.á¤ë ËWo­.ÏQ“¦bá%õa¥;õ -÷ù0÷S½Ï(û 㻣(Û(•!‹ É8ƒó•OÕ"¯p±,÷£(•ERÁW‹ÙTË—ç8‹#·.“ís¹1%«%—µS¿1å&•Ãƒ“·Z÷“\ýx»*ŸW¿‡ŸïƒË!©’ñB©aÑ~¯SÓœ½b»¡±шÍšçM¡Ÿ„¹ Åd×­ïm£tçLÓÇ…Ñ9Ý -å-ÿñ'åš3ÏŸ×&Å̓ÿ¡‘s™Œ‡qÍu­IÕmÕ<¡Ó[£Ÿnß ƒó[û7ÕÓu›¥hÿ>É©µ”ï@¤/Ãíï"iÉ­›NŸ?Ó@ý Íų:ç7µ© -™•¡ýríñ ×Ý[×6¯ Ç$Ýmµ û!‘>8­ÅW›eɵ»ß9£BóŸ>å8‹5¹>…:Ó ‘C—5¿S©³#‹Éq£"¿“s×ë''¡@óu—/•"¥på“4¿!9_?£"ùPY…¯ŇYŸjŸ ¿,¹!Ù_Ù-5¿8µ(û WÑlû韙yƒ[¿7Ç“”KË¥ƒ™kÓ•§m÷óõ…P‘!ée£BÅË’»¥‘‘^‡ ñhåŸËó0¿e±¯Ñ ×—“·f -8íY£“ -£LÙnó ñVÛ ã=ÿ é‰:ãC¡ -ÇNÉië"µñ}ï(¡ Ÿ6§P½M©7§óx¿šû Æ« ÙO·!ÍY…“5ƒMù Ó!±’É ×!•7·lÅ Ÿñ™Cµ9¥ ÿë!±× ýEï7ˆÇ$FÕ‡£9‰7‘Në8«3½NÑ#Çl§’á™K—7ëañ û,½÷`å ßaÿ §•™ -ë9ù;Ã9Ù{•Z¿#³b¿8¥<ï -‘L½5ë\Ñ m»!0ÿ Åg‹‘Sá ±W… —_ÿK« ï"ÍÃ7•?×ýS™é••¡µŒÓ0ûD‹/÷&ß«6¿Ó"ÓKƒ+³%¹#ën -ç$Q× õ½GÙå -·ó£!Á;—“—ËDÁEÿG·‹±‹ÉgÁ½$Í#ï%ý+¡½ÿ¥"Çjß" õ€Ý³ é ëï’ù@» ¯_…M™zé89’»eïA§§G÷;Ù`Í"Û‹Ÿ— -Ÿ¿“ÏK½7ç)Ñxéaï>ípÑ"çVÛ ËïZ•,Ññ©ÅqÏ"$Ó ¡é‘…&z¯¡÷6ɹA‡ §®ý˃a¿8¡jEï¤Í„¡"Ë1—é¯%Ó{í_ñC«:Ãý=ã¨Ï­w›—¡Ï_-©ÿ›ë(!ï$•Iƒ7÷3ó!¿ªËû ©H±`ç™».Ñ©ÙGaû¥+¹Ï®Óžíà -ë<ßWë³—ë,…s¡—CñW‹1™uƒ-ÃS‹OùC߉Ç]ÿŸf‰“!¹õiÿƒgåóV‹'±Í!Å)Ë5ŸlÕë¹­‰Û‘ÿ#ÁN¥‘ר·6‡Uï#«4¹}—‡4ÛPã—Ñ`Í ‡o…Ží ×Jë ¿¬ñiÁ “qÛvËÏ :¹‡Ý±¨­OïN×x©*£ïëY7ÕE£2ç&Á€Ùõ‡éj™4Ãzá–©ë;¥£]ïÅ­ÇF×W‘™·%­fÛ­·9çBݪÉnýcù{‰®¯ ƒ2Yó*á”›&Yûm¿GŨ‡ ç?ÿŸrWûM©ŸkUÃ#—o©±Q­lÁ™&Y׉ÏU€c‹J—ëoÉAˤ¿pùçû”á“'¿o‰£ói‰Íëƒ[µ&ŸóÁh›+¿~k‘KÙ²•y½R¯–¯°ïDÑIí1Ç-;í¯›:å1›±£6‰«uýz¥õ£cµ6­0Õ#OÅ¢‘E…›-ËDƒÑ)·C÷$‘ Ï‹ï—ñó”¿3¹`»tå—™„Ï5ݲ¥f©sá«5±.Ëi‹/ŸwíÏZý@/›Á¹>ïa;9£· 韓J5¥9‹Û4™3Áwé3½ -¹R×É©tÇß2…ËÝ=µ%­œ;ÃÕ“pã)•#­¥ ˵&?à ­¿9§BÇ[ûNéõR­‰w¥7—°•¨é˜·û–ï=É5§L³°«;ï -±Ñh± -µVŸˆ×‹_MŸ,Ýr»™Ý ‰ ¯híŒÏO»­õ~Ù"“.ý¬³O"óœÕSÇ« ƒY¿>‡ƒ«OñGóÃŽ—L¿ŠÍõRŸ‘xéÏMÅÝŒëg³µŠ­…¯û‰Ÿ¯vÿ¹­Eã¬Ë"ï%Ÿcç%¯6Ï8•ÝmßC± ½‡Aç\ÝLíM¹«Í]Ë7󆛖›gà Íxù ÿPÍ «”Ý5Óa™±{Ù&¥2™6‹ Ë^ýtó6‘PÅ ™$³#Ÿ³Å3¹»—9•“«›±1éŸ:«Iñ ßMÓ€·!¹ížÕoß6±k µoõá cÓ û ÝŸHQ…[ß0¹­ É -ý9{)ý «k«×hÁ -¥EÇù9¡ _•,¹!ñUù -ÿ5YƒÃ9g¿máD¹‡(÷å8ù+Ùß$§í÷—*ÉEaÿó—"á -µzÉ“µšÏ¹ñ!ÿ'cý…•Zƒÿ#‹7¥I½:1‘#écû"…o‰ -ãDý!ÿfû¡™¨Ÿ-å"ÅJË ©9ó ×@Ÿ$­"Ÿ¡(ÝP­$ó -ÿ8É%Ó ­:·9‡4Ç ƒ Õ<±@ñ$õ‰99í#éõÏ/ÓÇ)µ#ÉO×'ñƒ ïNã÷<© ûAå%¹"(û…¥×L‡"íÇ4?ñ3¯Ï ×D»+ý$ã¥6í×lûÇ -Ó'½C¡ Ã:õ ß)JÇáól¥ µå7ÛõFá« -ÛPÕ>…*¹‘ ý6¯ -é4‰?4“©)ƒ9“‹r¯± Ñ­¹8Ë%÷#ã(éå8·@µ © -éOïÝ4£>“rµ"‰E‡.Á ­Ñ&õ!¯RçhÝÝ•"ßnë— ŸJÃý!ÑPÝ«›0Ñ·¡‡XëEí‹9—•|›§«1‹Ÿû§vÇnç õ …7Í>ûLé*Û/‘"¿]× -÷ ý6ÕqÉFÙ ‡+I‡’û"Ñ#\ñ0ß]9‰dYÁ ó‹z¹!‰Ó’g“(×|á²Á]Á&›ñŸ›IÍ3Éõ ç3ŸÑ å&ÅK±Yóé åV³µ9«2óI¡+ƒ"ù‘®ù)§då¥í©±ÝO±c׋Û -“lÍ"‘*Ã]ƒ˜Ùf™m“å•6‘'ƒzÉuÃZ‹€ßEà ‘ˆÙ7ýK—yó¬÷%±Sùá&ÅÑu›÷‘%‹EÓGñS¥ ‹,©KÁyÙÉ0ƒ³2µDó‘Ë9‹‰©c¡ãWÅhå'ÏÇ 5µ§ÛA¹9ƒÁ%ñ ñ­3Ï3•5ƒ íÛ ¹*Ûœ©mÁ…™^Ýõ1sÙß&ýùçÑ7§EËEÙ ñíÅñ3×Ç|ë ¹Á'ƒ.ã Û3×óݬ“Uñ#Ÿ!ý}Á‰©"Ý… 5×!Å?»å€é¹ e©fÉD‰FÉñ9-½ªÃ9Û~»¡¯§õ© ¿6Q½ˆ»<ÃP‘‰±-áëv¯x·SÇ>« Å!Å7‰7ó<Ó>» ·‹#­D‰‡LÙO­ Û;6‘¿Q¯ Û:å)õ ½_¥;‹kóë •<ÕBŸß8åÿ©5éA‹;ã ½DÏÑçAç«ÕAµÇL¡]Õ3ÑF× 8±!¡IŸ ÑDσ*·:×3÷!ó8³9ñûGýJùO¯•#½*¿Aá—‡ »,éP­S‰“3« -ÿr¥à ÃgÇ!ëW÷xÃ"áyÛ½ ‡eÅã˜wŸx!ƒŸ©Ÿ Ã:ïŽ#Ë áŸ9Ã^Í6Åz×3N¹:³‡óÓ§ÉKï_ŸSÙ!«ù÷ÛZ­7™¹“ÃÉ7ó ïG­‘"‰0¥WƒõJù6Õ‡Ù£™U­—«H©"°í¢©“¹­‰Z“A'ÿ•&͆ÏÕ#©™$ňçk»+“z&ýˆÓ|Åo¹4œ§ãÝK× «g3·iëfÔÓ=µóvñ) Ù†½Ç&™Lëˆåç“NÛ6É -•!Ÿ· ™#…s£g—>ù·"»S¹Aå<³/¿ã}ó­*³IÉ^Õ\™y3­vå ;N— -½¥ ™¦›!½"§R8Á,õ0‹ ×Ç•ááªõ‡z÷-›¿©n¡×@É -鬳:™³çŠ¿‘ÿ 塃}¯eé ‰œ£ãiïœÛoÇ&‹8&ß{£ý ÏÛ[-¡Léoà -Ó.<—iÕßtÿq¡­b›/± -ÁSù†é'Õ~˪Ù¥6¡^™g‹[AÃGÛAý±`é8éyñLËW÷7RË ©ù‚©„1Ñ+E­i×õ4çÛS›GƒW•N™R½Q˱Mß-ñ€™6éT‘&é_Ñ Õ -×S§"ýcÅ‘]ÝWõT6…Gµ ýFõ=™(¹'¿ù#ÿ†½D—³{µƒ‹çzƒÅ­ ¯•Å<õe‡%Ùœ—F½‰›©&ÛAã)ÙŸË4ç*»‰o¡GÕA“où ù‘Ë érõŠ¹…M·!‹Ý{±Ûœý*½@ÅŒç‰ÛOßÑD§8‡2ÿNá5£u±Ï~­ÕXß3¹Då¥'í¯[³eé"ã‡uÉ‘óFµD"Õ”Ñ@ÏVÿ·#ý‹Å±«ÿ=ñ™±–±VçÏ¢©©1ß«¥Mµió0åQÉ0ñ¡™íUÑA× ×¥ çzç1Ñ™J§eÁ… ë -·@¹ŸÑ49Õ•ó]ïýlï ŸÑ+—™ƒz±=Û -ÑvóE— ß’f‡ý:™ ­ezÿ?ÍHs!³»V‘ÓCÕ6õz— Ý8 ín­Ñ8é—é™v¡…#£Œ‹#Ï •D‘¿£!“€©ç*±&ׇ&‹Ié0¡‘eí/ñÓo«#͘Çõ3· ß—³ ýÍ7±CëÕl÷6µƒ‡9ùõëwñ£!–Ó -ÏL¯ ¡oï"ß -©tý!Ïpé(ï@Á8½+ÍËç‘¥ñ3¥‘0‰&‹é½$ý%ë#•'HÕù%«£…3ÍÓ÷׫[™ãï:­Z@³~Ù/ǃ&Ïõ·³ÿ)ùPÝ&á=Ÿõ…ÍÙ¯!³ ¯RÍ0ÿ »ó­&ß=³Ã‡‹)¹ “ÇÍ ï •µ7õ9›1‰ Ó!‰é#™™ã“$“!©'é%¡0çññ ù÷Ç&É(Õ‹í å*,ùJñ³&ÉÙÝ(—ë ‰Ÿ Ÿ>© Ý!³ƒ+=ëßï%ù Á -˫˳ ¡¯ Ï{°ÿBÑ!×8*Vßçá£&‹«F@Õd¿6ÙQyÑ¥AÁ85Ÿ39Ù%+ÁA»4‹?é?9·[Õ‰å¯8)éE½ã,í3Ó Å½ë!i•9‘b5©7ÛSÃ>ÉÍ-õ/‡®½Oá­M1×8Q;ó%™:‹‹8Ýõ"ë9· -ù8×*é,»A±*‹ -¯Rí —$ß9›5ß -ó0Óá‘GÍ<Ñ£:Ã4û!Å:‹0Ñ ·4Ç(«"‰0ýƒ§ ÝJ›"‰4›#™"•Û5¹1ÛŸßa±!Ïã­ÃP¯,¿A· Ç9£ïBé0Ñ6Û0ù!ûŸ*Ñ+ë6§<ã‰B‘ óO¯çB­­!£©')t)T-Õ`-»9ñ‘7é<·“$Å -»~…ÿ ‹‘£YÉgË$Ár²•³«Z÷ƒJß Ÿ<ï‡ß2½ -í‰ÿ4‘JóeÙ4Ý-å@Ïfõ,ÝN©ÇÉ;ë:ï`¹pù(©z±ã§±BÍ~§Jµ\M‘\ã×|ƒñ¿ÝEç.• × Ó_Õ?ƒ%›‘TÙ½€ó„Øñ=‘ŠïqçI猓‹DA·2‡LÃë!¥6A§©ÃíBG©A‰ GÅïó ¿ÙHç)µCñÍùç(oï·¹»MÙ!³Û©0·Feñé)»;×8uõ+aÅ -§6¹*§÷+‘“ñ8û÷aÝU¡Ógí©aÍ0ÿ$ý"¿!]ïDq‹r•å8ßZ9÷6á ûF…Y×—5§[Éÿ.§—#«ÿµ?é-O!¡%Ï*¯ÿ%‹nÅ -cÝ‹Pç!C掠*ï!ó")ëÓN¹ký­( -µ ýO™+‘FmÑ6£‹,W¿A“#Á“cÃ!ë`ç¿$½AKó*%——7;íAÅÁ+Ó5Ý7sk·D­Q剋rwó “¡oë!•ƒ4—ÇMß6× ·³ åå2ÅP¡'• -á6IóF½y!õ%‘;…2£¯!¡"Ÿ¥ƒõQÉ ÿïl«Ë ¯4Õ7YÏ)³.± ‡3ýû_ŸA³9›(»"Yµ>Ù‡qi¥ó ½‡#ç¯A‰,­Xk· ™7ß%Ó#éOÕ ßŸëí&›J³ó:³§!:±#uÛ7Ç9·e·Å.Ç6«"Ç¡Á ó`ß~›?5›QÇÑ=óã#'õd±2+§c‹#7ÃÇ6Õpá!Aõ%­A7ŸW!§+WU± §^‹"‹:U/‹ñ0¹?µ;‰=;µ NÃ+eÑ ¡7ƒVWÍÝ8ÃEe™Õ!¡®Á“‘9¿˜¯ûÝP»‹‹rõUÕI£#ùk›¹Ý8ñ»gÍ -­m¿/› ¿„ƒÏR—l³™÷"¯‰TŸŒÿbÛ^ËvÕ ‰vå%‡›!¥)…Eç"›Ùxç3Á Ñ‚Ÿa¡£")ñ Ãç#õç7ÓP‹.ûy÷+ûlá¿£ É ùcÕ•AÅC¹2Ï(ñ¥ É"Ó#ù2» Å¥ª¡Žï!‹Û›•aÝ £PÃ?™ å4‡ -Ãï$‡ ‡#ù -û3<§‚£3:ó8U›h¡ ‡“ VÍ[µL,»6÷RåÕìã σ Çi“AÇ+áã(qË…ï’½ý%lj#¯cë“7˳>¹•õ5›ÕN¯ÇU‰i÷ß}ÑžÉ:Ã?› -éãÿUÉžmÇE-Ï »)Û.ñß‘8 -;‘(»I­8ë£U6‘Ù#ñN»Y“½ 3­89ùÿëÇ0ÓIãŽà É9×(Ù0±TÇËÛ -ÝQ1 -µ‰‰ ©íǦÇo3™ õó4©?í%ïX½­#ã‹õu£fÍÓ/Á«"Ýé„φ· -í$å|`/©¯»#U‰%é‚«*C‡)‘«+ý )ó í^¿!—Oï’Í?Ù$Ë¡’‡ —7™{‹8ÓÙ «^×KË— Õ$áy7© -å.•cŸ7ów“¿K³0Ó íl'Ï -ËX)©!é*ë{é¥ób9'åZÿïÅ!ù.Ÿ"ÁC× ‰Ç ÏF» ç…ÅG¥7™i¡ ÓŸš§ »;¿ ™3õ «}Ï! ù8‡xÛ7§A¹ Ó\¥ ûxÙ8ñ!—z¿‘¯9ã“9™s‘"—˜ù ç·E×.³7£¥B³[Í7“|í!ɹµ ÿE¿5ï5!×=ýݯ8ƒßyÉ¥‘Í›#íO¡!µ™&½í7¹GM•6·V…!£Pùû Ã$­bë1ãXù“÷?×çÅ.‰ûÃQƒÃé#½&ý#¡ §6Ï­Ù"õã»6Ù]ãÓgÑ"áýX‡S÷;»óPã$£?‡ ·0á7Ç>­(á/Õ9óZÏ+óÕ!É›[É&ù ³<› ëƒÙa»R«íKÅ0Ïçcç‰!g‚±™$_Á"Ç<é åÝ ÷b±HƒÝxûÓO• -ù\•"ÃýŽÇ !»6ñ˜ÍCß¹½Z™Ëgç£ ßï“)íP‘ÿ™!ùµ ‰*ùJ—.Õ ·(£ÿ›/÷J±ýi• « í!é6§ûá$Ó(ë%«*ÛKå÷:µ—$¹<ý%ÿ«0á ¹Å‘× ×+± Ã*ËHÁág‰#ÝÅùK« ÿà ¯{§¥ÍÉgËïN£ßó%ÕTç ¥#Ù -m£Uà -«*Ýn½ E…4ß%—Ù:Ñe“ ƒ:»å »$¯N±¡,‡B'ýŸ"»‹9ý"Íåó••¥ïí)¿Bû¡;¥ !Û‰J7<ƒ¹ëùý{é ËkùÉ@áÍF×M…¹½#•ïY͇Ká.C¿"£ë:“,Ã##·ñ5Á•çû7‰'û%Û‘M‘3‡4§”ÝV—;Ñ™ûIõ(ñ#ű5‰Nµ å.÷'óY¥9…V™ -áN¯3ÙN‹?ÕMÑ%·BÉÁ@ÁÅu¡.·ã"©`¥=ó ãßE£.Ç -Ÿ‘E§ ÏÁ2épó…pÕžÛí Ù›háë>Ó<Ùï1ç7¡Q¡óƒ¿«é‘aƒ­Põ-ÿ¥á?à -›ï[󚧟T™Ãù}Ç%8×Ý ¥Ï)·9Û:ótËýÕh·k£ßÛƒ…=Ï3‰•Á««ùŸ"» ­7ï*Á é*ó5—“ƒ™ËOåùõÛÑAÝ%§ÍGï#¯ÿ ç ¿9¡(é á(ï Ã9©‰Á ‡ Õ>é#­.ÝŸ7ϯ Ý8ã­ã½NÉÁ Ÿ'•å"ƒÙé«9å×`¯‡’õ¿ -á5— -¿1÷© í6ã% § ±M‹‡í"¿ õ/Ÿ û™Oßåë$™Ç6»Å1©¯"ý•…›#ã±&±…2õý ßÙ#Å!Ï#(¥µ#•(×"­"×õ— ƒ&ÿ»Hñ ï³7»ë$Ù éÃ#©Ë!£ Í9­2™ ñ ‰(›#ÇD×,¡#½½¥ «#•Ï"Ù-Õÿ ƒ¿0û ÷±"ƒ(±4‘ó.«9Ýí9ûÍ%Ë0ïÓ!—Û_µ?»K‹™]û1çwÉ—¢YÕ«bÃJ­˜É³ƒTí¡ƒnÁ³—ý -hk•rï!ÁX5ƒgÍIãÿtÃ(¿…‹™!Ý4™*{eï8ëå0¥Të£-ó0Ññà ×ûaé&½é3×ß‹¡a÷…-Ë(åV“U ³17õ*“&ÝÑ/ç>ã"Ñ÷ˆÉá׃Xû™¹,í£%ë!§•1÷P…ù½bÃ(ç Ç8ÝÝ1Ç«,¥"¹0·QÍ-Ï ‡4Ý «1åµ+à ó·ëCÅ ­0…Å=×»6•’‘2»6í"×#ÝPÁ_™éDý/·66Ë -Ù-…í»~Ù ¡å“ Éb¹­_Ý1å÷ íW•&é óEÉ:ë(ë“#áëJá Ý"ù'ù/Ï»&³*Ý)á ‡ ÷(Ç áEÑ3ƒrÍ××]Ź…z»‘·må!í»!ÿ÷c•}å<ƒ\û ¥WÁ —»§ó1ÏK½=ÓÙ1“… ï(·é"•í§1ïJÁMñ$¹ß%…OÅãÑÇB›“Á˯ù=ƒ«hû’“Vçùs«kß#ëp¹/­¨£Bá—Õ‹ŸX›2ûKÁ4ã1«CåGÅFÍÇß‹;ÿ?ÅAó»ë9]ÑGÍ%ù3áÃÁ"½:ù;¹ ׫:± (Ãý å#åT±"×å™NçÃÇ£<Û­™Ý"Ïaÿß)˹ »8ŸÇƒ›ã'õ Ë6¹§Ç ù+Å'ïù(³ Å÷"Çm‹L÷9çï -õ!Ý=±ë©WÓTVŸXÇDé@2çß!»+ûã"í$ÙKÙ…tñ³Ñ:­$ñ<å=Ý5•)£"óÉ+©óÝAÉ6­>·¯ãEŸKχ ¥µs3Ázã½ãcý/ƒ ‹ é:£:á'• “2¿ -ë08»Ý}¹!©­jË&ùåD…« ¡]…~÷§ íJÑ#±*íf±÷5ÿ\¿ -é4—D‰/¥PÉáÁ:ß?×ñmG» ù§"Ë%á,§-•FÙý$?¿•Û8Õb½8ƒç-•P• ½6‘å5á5½:ñ Í!/ƒo½±Å|§ˆÇ2í6×3CíñDG£6í7©.ç 1…Rýç éLá.Û …8Åq7Åå8³ ÏÝ4×Ý8勵©b­Ù@·K™ÑA©Wó·’×#/£—>ó"ã£/µ7‡› -#ÇE¿+±™ ¯­?­1ÑÇKñ ×6Ëù"Õ¡qQ%¡t¹¤õ‰U­:Å-‘>ÿñaÓšýˆߢá&+ó­…§ -õÛÑ•‹ÕŸ%ù£oé)ÏAÍAã !Ù1µ@ÕMÇß«&ù¹@ñ>9ë ÷%/¥O@#¿3·<‹A‹%/¹r-á-CÍ[ý)ór›×2ë>©ÿ.ãÍDç(§¡Ó&#ÛE·3Á[‡:Ù,«­é7Ë«7•«:±Gñ8û{“"ï¡:û=ó•%íŸG‘8á ©7… ï¥E»?¹<¡6£4Ù%ã#£ ß8å ±!›xÝ%ÇyßïRç©H­J§Ÿ‰NÁ•Ï ‹Û¡0¹ -·Hû¯çOc£ß…Lß!ÿ# -›•É4õ8Õ=Ý -éÑ!áý£F©»)ëÕ5Í7“šñv¿Ëa<ýY·¡‡¦¯<­Ã'³‰¡XÉ'“wçÑ’Ç›¥V×…£%¥¡‰õ.³nÝ©¡©ÿ)iÑ;• ½»8õ×l‹3ÕLÃSã"&Ã@¡nÛ›c“1¥­z«(£CS¥>»0DQ½]Ÿ マ]áa¥3·UŸqï—@íhË¡n­ Ó"épiÑÁ!Ã)BÃ~iÍÿoS¹AÙëA§µ×GIŸÇíAéS‰–±áAÍ)±vïáeQ·G±#Çï@ËEKûó^Qõ=Ãa•|ë>o±C‰Y‡8“u—n¹+£{ÍmQ›PÍ ówÏ­!™9™³?[Ï7ÙNç}!‰o·LŸ?Á.­O±ëE‰‰WŸ £y_±3ÿ7ÁŸël×F÷_Eá#ûVÅDQÑ*‡eÝ,±Ë™0ï!¹2kSûEW¹X¡ -½Lw›D¯9¡La—>å@S»6ßl鯧|õkµn×"…!Í… ©“·‘ƒ ÷õž•› ‹$ëoëm×7—#ÇQË”©ƒ›[íQ­Çá -ù󧡫ƒMÇÛ(±[µfZ‘-¡Vé\«©ŽÓ‹x©(‰™ŸJû7ƒŽÕÁÙƒ¿±±©³zËRt׃ë=‰P»LïÙ\Á=Ëý—&›ý8­7· ‹dÓŠÿW•#÷¹ í.ŸP‡­“ Ý ù`ï Åë?÷™É¿ãKù"Õ>…„¡ï -™<Ï"ÕE¿$¿YÅÏE££ç6#µýÉ7ÇÝ+ñõPé É Ñ#×­5“ó­¥p‡Fá=ƒÓ*Ý|‰(½tùåÕhÃéý>û ¥, µAó™Qß!§¡a¥4Ñ -éP± ùß&ñ%‰­pù·•»Ÿ/»· -‹á ×GÛ Û‰H‡VwÙ#· ßF“Ÿõ°¡Cƒ *­7©>ó9© Í%ƒ™"ש"ÍB¡™q½9—]¡"ßÏ›oÙ7‘¿$ÉX…¬åÏã«v±» Ã#³_Ù ‹½4ùqÇ0ï ­¯‹!§ÇÝlƒ„ÉB|Á(Íxõ4…"¯3Õ3û¡Õ„ñ—V•B­[•'Qã!ùJ­+åb¿(ŸP—ûfÕÕ„4ýuñMù5‹~ÁRû4ÛX6=‡”ÉÝP‡½\ï­Wí,Q½·\ÁÉxÕYÉQÁJûJÇ•… -Ía¡ •^¿&³Ç)ßV¹;ûLÙ3•a…(ùõѹ$É,éAÃ:Í …@ŸC· ‡#™ -­ë±ÿ«¡ª³õ6ó:צŒ‹ —u…\¿H-áÑyŸ*¥nå·oÿ&Ûу“žÙŒÉ Ó«ï²Ùž.ß|ÇŸõù¦­^㘃C« ͤ?¿@7Ý'ÁÓý寿¢ÏhÙ(‰ËátÓ‚‘­ -ƒÑQÙA»— …€Ã%ût¯ í4«i‰Lù½ŸQóa¡†ÛªÙKõP¡@ÅmÁ‘Tá•*ÍOÏAãÛ]›û'•$ï ÅJßh½ ƒ\—7Ç/÷aµËŠË…h‘Qù8É­>¡IéE™© ïVçë$ÁKÑË«÷@¥Uñ: -™Ha³vù7ÃM×`éÍa©ùMÅHå>rå[õµ É;³`÷ŽË¥‹Ï6ádß&Á¯…í"·Ï<—李 ¥ ƒ?U§%»!¡É9«5aí¡í!£e‘Aáï·#±£ -·ÿ*·I_Ÿ:ÿÉ`ùg³¡ýJ‹”›>Ù›q¡BÏŠQ‰ï Û~¡DÅ4…ÁTÓXË„ÕtÉ> -ãz·÷Vɤ×^£@ÛBñx«D±‚Íp‹§ÿ­Ëmµ*Ǭé -£ÿJÕ«`­ýšÍ–%Ÿ_¯Í.ñ›Ÿ§ÙX‹g/›ÿ4…SÙ Ç!ûZË&ÓïW­ ëTå Ñm©áY·>ƒx¨›5óžÍ1ù„S“†ÃÝ™r³“•‘Ë?ÿ屩d¡ Ç™Ïiý•©D­—>á@”ÉwÉù3¯ ë!×Í#ý*ý0ƒ"‘«;µñUÑNÍ=•ß Å/í» ÙA£ ÝZå*éÙ -ß‘ -à -ñlÇÉ,û9Ù'¯•@ËgÝŽÑ]‰JM³Qcóß ·Ó§{ûs³Ó:ç!±É¿c¥.ë3ù7Sï8‡•b·™ ûårá ý -µ¥níÇËÅFéÿ*ŸÅ+tõ“#“Ó ¥8í“-ç~¥¡é ±³}õ­ת‰—“eO—·óÓÙñ£÷"õ;¹³·£™ñ‡sÿ'Á`•Çƒ™cå\DÕšÅ&ãAù<ÅIû§—&µÁ6‰jã•uû:Ç'ó¢é#±F«{Ë®™צÍD=Ó`Ýy“C—2©Ñ »lá -½3›dÙ§ýQ‡.ƒ¥±oí¹ …©¡Qà ý|» ¥Bµ ÇLÿ Å· -õ—ÿ,ÁÉ ™wÙ -qãåE“)çn—Tµ¡0½@…z³ŸbËC— ¥?•q¯ˆ±xÑ…³Ë~ѯa­?ÝI»m¥"«]×DÿaÍû•HK‘8©P‹4Á8Å@™ ÍŠÑ–™“6—OÇcó‹8“.«ÕOÝdÃçëF›ÝÛ™D¥8½iõ ½p·!±@Ñšû›sÍ&í€Ó ó"žé…ñ®½9á†Í·‘¯«Õ ßn‰ -‡¹Ný¡¢å#÷ˆ*í[óUŸ)ŸF÷l¿Ž—í¥‹=¯ “jé!·W¡pÝYסÍgŸ4ñf¯ñIÁ5ÿÉ_ù÷•» W‹’«)¢± ™—¥{Å…áV±qã•£Dû$Ña‘ ×$•‰“ˆƒ&Û”‡‚½¤ÓFçDý˜ãF“Ã,ÛÝ\™¥§‘g“2Z÷ ×{¡“F÷*§%½‡×(cï ýA­>ý&ç‰fÃï?—?Õ@§(áC¹TÑß0§'ßDÑ(¯*‘‡f¡xÑ%ëjû¹…xÛ(ó©@ñ-ÅM©©Ç'‡ךчj™Û{—¯ÕNÑÑ7¡ ³Bý7ç÷™§ ý_ÍQç’õ-/Ÿ © “:å «~ó í’׋#÷¬ÅrÍ£¨‡5…3ûe‹%׳ ‡^©;•{¡Ÿ…©«³›“ ›„5¯»s¯@§SÕ+ƒ/ч­a›DÕx‰¤¯ ƒo¹=¥“Ýn©¯4±Õ¨Í9©hà Yƒ5É¥†Û©û×r‹aëÙÙσ`‡³³ï÷k¯#½§Ï ÃN“ -ÿLÙÃËálÍ©O¯Ÿ‘$™d‘¬…q‹9¹]ã6£o‘–ù‰)õ Á@ã -áIí=É=ù »çÛÙoç ›¡qÓ!ŸÅ!Ón±où9«8%Q+ñE9µ#ñ ˃C!Õ“ Û%Ó+‘#•&ƒãR¹ -‰<75«Dç'›$Ó+Ù@¿0‰ ù?q‘½"ÿ‹ ñå ½(§E7©·!í0Ç@%ÿ­M'ãñ0í3Û#ñ ¥(ÏëJ=‘9½ ùe›“ å±MŸ -§W•#‰á'£KÍ­@«3¥é;›A³ µL·0¯ ¿ùgýÃ2Ÿ?ù!»5¥Aù×+‘Që» ÇWù×T©"Õ‘)Õ—8Í ë"÷D‘4•?Ù!Ñ ÛJù/Û×ßD¿Ÿ‘…íTˇ!‰(Å%Ï`ýÝ ¯»h¹(ó‰ à -™ßR³ ßùí)Ñ­9— —»§.…"é=Ù-“#¯Ë í,—M»é ‰C%¥Õ ½*­!Û÷<½ »+ù"ï§8É0¹—¡%…ù<›ÕL¿§9›í&/í$Å6ë<¥ -­Lß*Ý­5¡!÷ï8Ÿ Á)ÃÑ+³ ›&‡ã:!Í@ó‰#ë!—@í‹%µ -ÿù"­ÉÑQŸ^áÅ4×ã¥uå¡Ñ×<‹5s·á§g»mË(©ÏR¯[ϘÕeÁEOƒý`¥4eÉ?Ý#· a÷C‰”Õ'§\Çc‘~Ù‘RÇ>ƒß/õ&ÿg‰‹õAI£ñb—ªÓ%[õ>Õ:½G×›ÿ4ý<íi¥½aé -E“½xûcíŠÏ uŸB¥VËV颓5#ãx›²½ ñ…m‰Ç^“· oÉ@Ñ…—@;¯±5E?¡;&íxűÓBÏE­!§;½¯­g¡*¯yß+»Cm£™7÷£DÑ ¿B;Á:©ë"Ï ³ƒP«'•±RÃe»=ÛÝ@ŸPËjÝe¡ÿkƒdÝT áõ>ãR¡±Ó6Ó5_§ …>ËT©I‘7»WÏ¡lí » Ÿ“é0é8W§#M‰XÓe­D‡1D¯ÿvÙÝ“ç›óo—?ù ín§ÿn?· ÇA™GÏAËA¡ß!ïA±Q…No½V½VÝ=ß4U9åaëz™kóµ8R•Ï'› -Õñå‡Ñ -ñYÅñ"Õ*½0¹@¯¿ AÝIË:ÉÓ4…¯"×¹õ £û=¹0Ý£7Ÿ¡S—‹Á“ÙhëÍ/å2û>¹)ÉÅõ+Í?¥Ý&µ—¹ÿ¯‘+»¿éb±³)¹‰ ¥Ñ‘(í¹.ù:™Ñé _‘Õƒ‹aãÉ ÁùZ‘Ç«8—)÷ý­ÓÅ Ã&Õ×ɃßUÙÉGýÕßåý×)ßZ«ÇÇ,©:—ó‹ß6Ý1Çeá™)Ûf½)­éb«³1»÷ÿK¯Û)ËûDËÙ&ÙF™'³ ­Ï‡«`÷é4“ùl_ùYÍ“sᇃ -—NW‡å ³ ñ•Zƒû+‰ƒ —]·5Çדåû瘿˅ù•QåQ ƒí'‹0‹‰D¯ŠËN¹½¥ -£Ù½n•ÃãóíY¯§ -ÿ%…#¥*å'×0õ#‘ë… ½÷·±×.³ ¿9;Ë?§Åóß?»CçÙñ:ñ¿Õ¿0Ÿ+¹½ë«8Ù¯$«×@ý­„÷áÛIû¥Íbý Ç1ŸOáÁç:áH—‡JуíïÙKµ'«¯‡G•Ù÷ó¡Û§?±EÁ¯ï åIãÕ!³ …\ɲû±¥,“Eë˜Ç;Ï·#÷ÛaíX³±*‰Ù#åKó -ÁwÅ9µ=óÃBÙ¡­W›ù9õI½#ËBÙS«ý•m±$çÑ"“&û;ýµ³!£¹©Í\ í!ßïT·FÃË -¹³TÃ&ý:åÉÍ6½ …a#ë'õ» ·Çë•ÕEÏ-±± ë û9¡(ʼn‘S© ÙÓ)íkó­"“?—1Ù(ÙÇC'á"·6Õ9Ÿ"•0á ù"=—£#Ã¥‡@Ý(ûoi ¡d‘ £ù‹§1ë?7«©‰K™ áK§‰=…™ ¿I™_¯û%“©8ñÑO™Áx± ó.‡a§!£m2×NÇdÝLÑ›³kÅ­2ñ,×`ñNÛÃ’٠ݥg‘{£Re‘Z÷O—ÓNEñÏ>ë™Ã³7ËÃg‘ã/ñ6ǻݞ¿³¿^å Ùba›9‘ …§ ïUáë’Ýã/ñ™ëy£Ñ…{û 1‡7Û£:«ù¨Á+ƒ ßšµ -•=ƒ#Á~É͉ۋ·íW« ÑŸ ó e‹ ¹9Í(¡cù;ÙMƒ ÿZÁ%•Õ’‘B‘ ÷€"Õ£7ÓÇ’“1ó6i•#½ ‹ çù;¥4¥M»˜± ᘷ é÷…u·4û©Ùvé5ûõ“Eñ8™˜× -Ï~‰'ÝH¹7í -Ÿ—!ó‘½2ùL³\áUÛ˜³ ߇ »r£7õ0å8Ë8ÙLÓÓ’¹Sùÿj›#¡lï ¥jÙ3Å(§n½cÕLÝ!Å-¡8Ë3ÑŸ}÷4¡Õï §a¿ï•¥t¹4‘#…ñ]Õ²µ{Û…}5óÛ ëí>ÇÓM½k£Ë‹›4×c¯±@í²é[‘7Å -?×ZÑZŸÛOõ?í ƒ%Ë¡4ï_I¡P·;±‹,›¥8Õ S7ÿí#»!ßiã$“[ë--ƒ*¯"¡±é$…A»Í6·7ÙJ]‡‹§Dá7õUÑJc³$Ï“>©¡ ¯8·ÿm)Ù90ç¡8›µ!‡ a©p÷ ¹$[ùl±]¯AéAù›eû#—Y¯9Á ­Û6ïAñiŸç[ñ· ¹q—Ÿ5ÁDûÙ"Å#·"¥qý|o³ c¯ñwÉaÁ…»,«tŸDûù9é7ƒn‹8‰CÏWß6ÛéSÓ±6WÅ¿S©9åbû ûSÓ?émD™/[»LÅ!£`û&ï·1ß(«2‘ Ïõó!“Q£!ÏIíbñûZÇ8ÛJ×9Ñfý1§0›&©·¤ùyÉ7G‹ ¹[¡ ß -ã g÷%›A© ݹ}÷(¹bïc«!ç;‡ÿ!Ã"ƒ°§§zg‹N×a»Á!½¥Ó ¥‰§ •§ ½‘«™aµ—µ7ù–£ÇbÁe·e… •#§"Áû?± -·5gÕ§J‰ÇÍ µJåA]³ó#ñtÓç!×wñ­ Ï9cÓ§©#·{_…moûU™ -M«“nÕlË_Sù$á;í+íx/µ‹_‡ ›£0uQï!…/û8Oã(Ç?W×$‘©ÏnÓWõÕ‡Í|Ã-™@Ë -Ý6kϽ9•/— Çv‘[ió?Ñ,¹n͈¹Ù¢Ù‘sËá ·]“‰Ý¹fiá Í8ï”ñ/ÍW“Ë ‰¢ƒ9qÅ!ß!çi¥ QùÉ#S• -É7±PÑ(·§±ƒ É»Bá8i¡ ù•·R±S­Ùmƒ —1a‹ -ï8\Áž‰ ¹…ý ‡k5‰%Ý/J• —cáBñ ã:ƒù6©£nå£ —ß#WŸmù'ÕÃç‘Ïÿ« ß’ßw£a×#á ýq¡½¹Œ­%Ý!ÑQk©²«f#Y«Kɨ·’ͱ‹i…gû£#‘ƒ É.•å•xï-é.‡­Í$³,e­÷¯§5¿0‰¯÷¢ÇÓ‡Ÿ8ã Ï ‘Å·9¥o¿°‹™‡ï7VÁÛ×7 ÷jݳ8µ ×™B›-K«LÇWå ¡Uã!™’ï -”+ï{Så;õj‡UÏ ]קƒ]…[ÍÓ6Í -Å]Ÿ[mÃ9å›l›,• m÷‡ï,õ— oaïg÷m‹×ë¥D‡DÓWŸŽÙj‘cåñõ -Ç“µó|åOÑ„ñƒMçvù2Ãé%_‘£6Ç=ß—9ß3ƒÇt¯j£Ã¥ùc¿JÛW÷žƒ‚ÿrAµ#½-٠é Ç8¡"Ï w½mé^±!Å¡™'ç£6û½„÷œû…Å oÙË¡"õS‘F©2ãÑ"kë¡’ƒy­;ó!—#K¡5Ùï#?×m¹Qá¯"¯ õ8“ Ÿ;Û`»5ó ]©Õ -M­[‘ù!û%kß7‰N©/Sÿ•«£Û‘ÉcßFK‡ ‰£˜e»{aƒA“]“©7õ…¯®Å—£Uá-džÍ«¯1¡Y½”TŸ;¹‹÷!µŸ…b³7… W…f¡ Õtcƒ ¯gÃ|¿ñï -Û ÷½&Åm_»¢Ÿ ‘lÍ!Ÿd“Z™¹?™ Ñ­ ÿq_™aÃ"çz½Û@³»6‰¡µ­“FÃ!‹ ý»°óhÝ û:]‹…« á3é:_·ƒíLד$U› ¯iû"ŸmûÓ©zUÝqÛFÕD­‰ñ -•©ûë »‡QËg™#¯"Ç)Go›#›’Ë#·"¯Œ(ƒ a½wßYë™Ùsã>½<óƒ"ï“Í6Ï;ãEU¡8« mÏ•‘½só@¿8_—‹÷š+“\k·Y·AéO÷¤»yý8QÁùyýA“7ÿ›±$}ÛÃA¹£q«ç Ù« ¹/Ç™<ÁÛ ³'±ïrý£¿™MÓÅ 1g·ß¯$±NÿŸ$¡­jÙ0ýùÃ,‡"éñ9× Ç÷“Åõ ëRõó45‘É í“ÿýCÃ6M—ËóD·"¹­ +¡› é ÿ:“«4¯lÃ1ÿŸïn‘Ãm¿7½/Ánõ–•»Oəǧ‰²¥(é|é—=ÿ!Ë.á¤ë ËWo­.ÏQ“¦bá%õa¥;õ -÷ù0÷S½Ï(û 㻣(Û(•!‹ É8ƒó•OÕ"¯p±,÷£(•ERÁW‹ÙTË—ç8‹#·.“ís¹1%«%—µS¿1å&•Ãƒ“·Z÷“\ýx»*ŸW¿‡ŸïƒË!©’ñB©aÑ~¯SÓœ½b»¡±шÍšçM¡Ÿ„¹ Åd×­ïm£tçLÓÇ…Ñ9Ý -å-ÿñ'åš3ÏŸ×&Å̓ÿ¡‘s™Œ‡qÍu­IÕmÕ<¡Ó[£Ÿnß ƒó[û7ÕÓu›¥hÿ>É©µ”ï@¤/Ãíï"iÉ­›NŸ?Ó@ý Íų:ç7µ© -™•¡ýríñ ×Ý[×6¯ Ç$Ýmµ û!‘>8­ÅW›eɵ»ß9£BóŸ>å8‹5¹>…:Ó ‘C—5¿S©³#‹Éq£"¿“s×ë''¡@óu—/•"¥på“4¿!9_?£"ùPY…¯ŇYŸjŸ ¿,¹!Ù_Ù-5¿8µ(û WÑlû韙yƒ[¿7Ç“”KË¥ƒ™kÓ•§m÷óõ…P‘!ée£BÅË’»¥‘‘^‡ ñhåŸËó0¿e±¯Ñ ×—“·f -8íY£“ -£LÙnó ñVÛ ã=ÿ é‰:ãC¡ -ÇNÉië"µñ}ï(¡ Ÿ6§P½M©7§óx¿šû Æ« ÙO·!ÍY…“5ƒMù Ó!±’É ×!•7·lÅ Ÿñ™Cµ9¥ ÿë!±× ýEï7ˆÇ$FÕ‡£9‰7‘Në8«3½NÑ#Çl§’á™K—7ëañ û,½÷`å ßaÿ §•™ -ë9ù;Ã9Ù{•Z¿#³b¿8¥<ï -‘L½5ë\Ñ m»!0ÿ Åg‹‘Sá ±W… —_ÿK« ï"ÍÃ7•?×ýS™é••¡µŒÓ0ûD‹/÷&ß«6¿Ó"ÓKƒ+³%¹#ën -ç$Q× õ½GÙå -·ó£!Á;—“—ËDÁEÿG·‹±‹ÉgÁ½$Í#ï%ý+¡½ÿ¥"Çjß" õ€Ý³ é ëï’ù@» ¯_…M™zé89’»eïA§§G÷;Ù`Í"Û‹Ÿ— -Ÿ¿“ÏK½7ç)Ñxéaï>ípÑ"çVÛ ËïZ•,Ññ©ÅqÏ"$Ó ¡é‘…&z¯¡÷6ɹA‡ §®ý˃a¿8¡jEï¤Í„¡"Ë1—é¯%Ó{í_ñC«:Ãý=ã¨Ï­w›—¡Ï_-©ÿ›ë(!ï$•Iƒ7÷3ó!¿ªËû ©H±`ç™».Ñ©ÙGaû¥+¹Ï®Óžíà -ë<ßWë³—ë,…s¡—CñW‹1™uƒ-ÃS‹OùC߉Ç]ÿŸf‰“!¹õiÿƒgåóV‹'±Í!Å)Ë5ŸlÕë¹­‰Û‘ÿ#ÁN¥‘ר·6‡Uï#«4¹}—‡4ÛPã—Ñ`Í ‡o…Ží ×Jë ¿¬ñiÁ “qÛvËÏ :¹‡Ý±¨­OïN×x©*£ïëY7ÕE£2ç&Á€Ùõ‡éj™4Ãzá–©ë;¥£]ïÅ­ÇF×W‘™·%­fÛ­·9çBݪÉnýcù{‰®¯ ƒ2Yó*á”›&Yûm¿GŨ‡ ç?ÿŸrWûM©ŸkUÃ#—o©±Q­lÁ™&Y׉ÏU€c‹J—ëoÉAˤ¿pùçû”á“'¿o‰£ói‰Íëƒ[µ&ŸóÁh›+¿~k‘KÙ²•y½R¯–¯°ïDÑIí1Ç-;í¯›:å1›±£6‰«uýz¥õ£cµ6­0Õ#OÅ¢‘E…›-ËDƒÑ)·C÷$‘ Ï‹ï—ñó”¿3¹`»tå—™„Ï5ݲ¥f©sá«5±.Ëi‹/ŸwíÏZý@/›Á¹>ïa;9£· 韓J5¥9‹Û4™3Áwé3½ -¹R×É©tÇß2…ËÝ=µ%­œ;ÃÕ“pã)•#­¥ ˵&?à ­¿9§BÇ[ûNéõR­‰w¥7—°•¨é˜·û–ï=É5§L³°«;ï -±Ñh± -µVŸˆ×‹_MŸ,Ýr»™Ý ‰ ¯híŒÏO»­õ~Ù"“.ý¬³O"óœÕSÇ« ƒY¿>‡ƒ«OñGóÃŽ—L¿ŠÍõRŸ‘xéÏMÅÝŒëg³µŠ­…¯û‰Ÿ¯vÿ¹­Eã¬Ë"ï%Ÿcç%¯6Ï8•ÝmßC± ½‡Aç\ÝLíM¹«Í]Ë7󆛖›gà Íxù ÿPÍ «”Ý5Óa™±{Ù&¥2™6‹ Ë^ýtó6‘PÅ ™$³#Ÿ³Å3¹»—9•“«›±1éŸ:«Iñ ßMÓ€·!¹ížÕoß6±k µoõá cÓ û ÝŸHQ…[ß0¹­ É -ý9{)ý «k«×hÁ -¥EÇù9¡ _•,¹!ñUù -ÿ5YƒÃ9g¿máD¹‡(÷å8ù+Ùß$§í÷—*ÉEaÿó—"á -µzÉ“µšÏ¹ñ!ÿ'cý…•Zƒÿ#‹7¥I½:1‘#écû"…o‰ -ãDý!ÿfû¡™¨Ÿ-å"ÅJË ©9ó ×@Ÿ$­"Ÿ¡(ÝP­$ó -ÿ8É%Ó ­:·9‡4Ç ƒ Õ<±@ñ$õ‰99í#éõÏ/ÓÇ)µ#ÉO×'ñƒ ïNã÷<© ûAå%¹"(û…¥×L‡"íÇ4?ñ3¯Ï ×D»+ý$ã¥6í×lûÇ -Ó'½C¡ Ã:õ ß)JÇáól¥ µå7ÛõFá« -ÛPÕ>…*¹‘ ý6¯ -é4‰?4“©)ƒ9“‹r¯± Ñ­¹8Ë%÷#ã(éå8·@µ © -éOïÝ4£>“rµ"‰E‡.Á ­Ñ&õ!¯RçhÝÝ•"ßnë— ŸJÃý!ÑPÝ«›0Ñ·¡‡XëEí‹9—•|›§«1‹Ÿû§vÇnç õ …7Í>ûLé*Û/‘"¿]× -÷ ý6ÕqÉFÙ ‡+I‡’û"Ñ#\ñ0ß]9‰dYÁ ó‹z¹!‰Ó’g“(×|á²Á]Á&›ñŸ›IÍ3Éõ ç3ŸÑ å&ÅK±Yóé åV³µ9«2óI¡+ƒ"ù‘®ù)§då¥í©±ÝO±c׋Û -“lÍ"‘*Ã]ƒ˜Ùf™m“å•6‘'ƒzÉuÃZ‹€ßEà ‘ˆÙ7ýK—yó¬÷%±Sùá&ÅÑu›÷‘%‹EÓGñS¥ ‹,©KÁyÙÉ0ƒ³2µDó‘Ë9‹‰©c¡ãWÅhå'ÏÇ 5µ§ÛA¹9ƒÁ%ñ ñ­3Ï3•5ƒ íÛ ¹*Ûœ©mÁ…™^Ýõ1sÙß&ýùçÑ7§EËEÙ ñíÅñ3×Ç|ë ¹Á'ƒ.ã Û3×óݬ“Uñ#Ÿ!ý}Á‰©"Ý… 5×!Å?»å€é¹ e©fÉD‰FÉñ9-½ªÃ9Û~»¡¯§õ© ¿6Q½ˆ»<ÃP‘‰±-áëv¯x·SÇ>« Å!Å7‰7ó<Ó>» ·‹#­D‰‡LÙO­ Û;6‘¿Q¯ Û:å)õ ½_¥;‹kóë •<ÕBŸß8åÿ©5éA‹;ã ½DÏÑçAç«ÕAµÇL¡]Õ3ÑF× 8±!¡IŸ ÑDσ*·:×3÷!ó8³9ñûGýJùO¯•#½*¿Aá—‡ »,éP­S‰“3« -ÿr¥à ÃgÇ!ëW÷xÃ"áyÛ½ ‡eÅã˜wŸx!ƒŸ©Ÿ Ã:ïŽ#Ë áŸ9Ã^Í6Åz×3N¹:³‡óÓ§ÉKï_ŸSÙ!«ù÷ÛZ­7™¹“ÃÉ7ó ïG­‘"‰0¥WƒõJù6Õ‡Ù£™U­—«H©"°í¢©“¹­‰Z“A'ÿ•&͆ÏÕ#©™$ňçk»+“z&ýˆÓ|Åo¹4œ§ãÝK× «g3·iëfÔÓ=µóvñ) Ù†½Ç&™Lëˆåç“NÛ6É -•!Ÿ· ™#…s£g—>ù·"»S¹Aå<³/¿ã}ó­*³IÉ^Õ\™y3­vå ;N— -½¥ ™¦›!½"§R8Á,õ0‹ ×Ç•ááªõ‡z÷-›¿©n¡×@É -鬳:™³çŠ¿‘ÿ 塃}¯eé ‰œ£ãiïœÛoÇ&‹8&ß{£ý ÏÛ[-¡Léoà -Ó.<—iÕßtÿq¡­b›/± -ÁSù†é'Õ~˪Ù¥6¡^™g‹[AÃGÛAý±`é8éyñLËW÷7RË ©ù‚©„1Ñ+E­i×õ4çÛS›GƒW•N™R½Q˱Mß-ñ€™6éT‘&é_Ñ Õ -×S§"ýcÅ‘]ÝWõT6…Gµ ýFõ=™(¹'¿ù#ÿ†½D—³{µƒ‹çzƒÅ­ ¯•Å<õe‡%Ùœ—F½‰›©&ÛAã)ÙŸË4ç*»‰o¡GÕA“où ù‘Ë érõŠ¹…M·!‹Ý{±Ûœý*½@ÅŒç‰ÛOßÑD§8‡2ÿNá5£u±Ï~­ÕXß3¹Då¥'í¯[³eé"ã‡uÉ‘óFµD"Õ”Ñ@ÏVÿ·#ý‹Å±«ÿ=ñ™±–±VçÏ¢©©1ß«¥Mµió0åQÉ0ñ¡™íUÑA× ×¥ çzç1Ñ™J§eÁ… ë -·@¹ŸÑ49Õ•ó]ïýlï ŸÑ+—™ƒz±=Û -ÑvóE— ß’f‡ý:™ ­ezÿ?ÍHs!³»V‘ÓCÕ6õz— Ý8 ín­Ñ8é—é™v¡…#£Œ‹#Ï •D‘¿£!“€©ç*±&ׇ&‹Ié0¡‘eí/ñÓo«#͘Çõ3· ß—³ ýÍ7±CëÕl÷6µƒ‡9ùõëwñ£!–Ó -ÏL¯ ¡oï"ß -©tý!Ïpé(ï@Á8½+ÍËç‘¥ñ3¥‘0‰&‹é½$ý%ë#•'HÕù%«£…3ÍÓ÷׫[™ãï:­Z@³~Ù/ǃ&Ïõ·³ÿ)ùPÝ&á=Ÿõ…ÍÙ¯!³ ¯RÍ0ÿ »ó­&ß=³Ã‡‹)¹ “ÇÍ ï •µ7õ9›1‰ Ó!‰é#™™ã“$“!©'é%¡0çññ ù÷Ç&É(Õ‹í å*,ùJñ³&ÉÙÝ(—ë ‰Ÿ Ÿ>© Ý!³ƒ+=ëßï%ù Á -˫˳ ¡¯ Ï{°ÿBÑ!×8*Vßçá£&‹«F@Õd¿6ÙQyÑ¥AÁ85Ÿ39Ù%+ÁA»4‹?é?9·[Õ‰å¯8)éE½ã,í3Ó Å½ë!i•9‘b5©7ÛSÃ>ÉÍ-õ/‡®½Oá­M1×8Q;ó%™:‹‹8Ýõ"ë9· -ù8×*é,»A±*‹ -¯Rí —$ß9›5ß -ó0Óá‘GÍ<Ñ£:Ã4û!Å:‹0Ñ ·4Ç(«"‰0ýƒ§ ÝJ›"‰4›#™"•Û5¹1ÛŸßa±!Ïã­ÃP¯,¿A· Ç9£ïBé0Ñ6Û0ù!ûŸ*Ñ+ë6§<ã‰B‘ óO¯çB­­!£©')t)T-Õ`-»9ñ‘7é<·“$Å -»~…ÿ ‹‘£YÉgË$Ár²•³«Z÷ƒJß Ÿ<ï‡ß2½ -í‰ÿ4‘JóeÙ4Ý-å@Ïfõ,ÝN©ÇÉ;ë:ï`¹pù(©z±ã§±BÍ~§Jµ\M‘\ã×|ƒñ¿ÝEç.• × Ó_Õ?ƒ%›‘TÙ½€ó„Øñ=‘ŠïqçI猓‹DA·2‡LÃë!¥6A§©ÃíBG©A‰ GÅïó ¿ÙHç)µCñÍùç(oï·¹»MÙ!³Û©0·Feñé)»;×8uõ+aÅ -§6¹*§÷+‘“ñ8û÷aÝU¡Ógí©aÍ0ÿ$ý"¿!]ïDq‹r•å8ßZ9÷6á ûF…Y×—5§[Éÿ.§—#«ÿµ?é-O!¡%Ï*¯ÿ%‹nÅ -cÝ‹Pç!C掠*ï!ó")ëÓN¹ký­( -µ ýO™+‘FmÑ6£‹,W¿A“#Á“cÃ!ë`ç¿$½AKó*%——7;íAÅÁ+Ó5Ý7sk·D­Q剋rwó “¡oë!•ƒ4—ÇMß6× ·³ åå2ÅP¡'• -á6IóF½y!õ%‘;…2£¯!¡"Ÿ¥ƒõQÉ ÿïl«Ë ¯4Õ7YÏ)³.± ‡3ýû_ŸA³9›(»"Yµ>Ù‡qi¥ó ½‡#ç¯A‰,­Xk· ™7ß%Ó#éOÕ ßŸëí&›J³ó:³§!:±#uÛ7Ç9·e·Å.Ç6«"Ç¡Á ó`ß~›?5›QÇÑ=óã#'õd±2+§c‹#7ÃÇ6Õpá!Aõ%­A7ŸW!§+WU± §^‹"‹:U/‹ñ0¹?µ;‰=;µ NÃ+eÑ ¡7ƒVWÍÝ8ÃEe™Õ!¡®Á“‘9¿˜¯ûÝP»‹‹rõUÕI£#ùk›¹Ý8ñ»gÍ -­m¿/› ¿„ƒÏR—l³™÷"¯‰TŸŒÿbÛ^ËvÕ ‰vå%‡›!¥)…Eç"›Ùxç3Á Ñ‚Ÿa¡£")ñ Ãç#õç7ÓP‹.ûy÷+ûlá¿£ É ùcÕ•AÅC¹2Ï(ñ¥ É"Ó#ù2» Å¥ª¡Žï!‹Û›•aÝ £PÃ?™ å4‡ -Ãï$‡ ‡#ù -û3<§‚£3:ó8U›h¡ ‡“ VÍ[µL,»6÷RåÕìã σ Çi“AÇ+áã(qË…ï’½ý%lj#¯cë“7˳>¹•õ5›ÕN¯ÇU‰i÷ß}ÑžÉ:Ã?› -éãÿUÉžmÇE-Ï »)Û.ñß‘8 -;‘(»I­8ë£U6‘Ù#ñN»Y“½ 3­89ùÿëÇ0ÓIãŽà É9×(Ù0±TÇËÛ -ÝQ1 -µ‰‰ ©íǦÇo3™ õó4©?í%ïX½­#ã‹õu£fÍÓ/Á«"Ýé„φ· -í$å|`/©¯»#U‰%é‚«*C‡)‘«+ý )ó í^¿!—Oï’Í?Ù$Ë¡’‡ —7™{‹8ÓÙ «^×KË— Õ$áy7© -å.•cŸ7ów“¿K³0Ó íl'Ï -ËX)©!é*ë{é¥ób9'åZÿïÅ!ù.Ÿ"ÁC× ‰Ç ÏF» ç…ÅG¥7™i¡ ÓŸš§ »;¿ ™3õ «}Ï! ù8‡xÛ7§A¹ Ó\¥ ûxÙ8ñ!—z¿‘¯9ã“9™s‘"—˜ù ç·E×.³7£¥B³[Í7“|í!ɹµ ÿE¿5ï5!×=ýݯ8ƒßyÉ¥‘Í›#íO¡!µ™&½í7¹GM•6·V…!£Pùû Ã$­bë1ãXù“÷?×çÅ.‰ûÃQƒÃé#½&ý#¡ §6Ï­Ù"õã»6Ù]ãÓgÑ"áýX‡S÷;»óPã$£?‡ ·0á7Ç>­(á/Õ9óZÏ+óÕ!É›[É&ù ³<› ëƒÙa»R«íKÅ0Ïçcç‰!g‚±™$_Á"Ç<é åÝ ÷b±HƒÝxûÓO• -ù\•"ÃýŽÇ !»6ñ˜ÍCß¹½Z™Ëgç£ ßï“)íP‘ÿ™!ùµ ‰*ùJ—.Õ ·(£ÿ›/÷J±ýi• « í!é6§ûá$Ó(ë%«*ÛKå÷:µ—$¹<ý%ÿ«0á ¹Å‘× ×+± Ã*ËHÁág‰#ÝÅùK« ÿà ¯{§¥ÍÉgËïN£ßó%ÕTç ¥#Ù -m£Uà -«*Ýn½ E…4ß%—Ù:Ñe“ ƒ:»å »$¯N±¡,‡B'ýŸ"»‹9ý"Íåó••¥ïí)¿Bû¡;¥ !Û‰J7<ƒ¹ëùý{é ËkùÉ@áÍF×M…¹½#•ïY͇Ká.C¿"£ë:“,Ã##·ñ5Á•çû7‰'û%Û‘M‘3‡4§”ÝV—;Ñ™ûIõ(ñ#ű5‰Nµ å.÷'óY¥9…V™ -áN¯3ÙN‹?ÕMÑ%·BÉÁ@ÁÅu¡.·ã"©`¥=ó ãßE£.Ç -Ÿ‘E§ ÏÁ2épó…pÕžÛí Ù›háë>Ó<Ùï1ç7¡Q¡óƒ¿«é‘aƒ­Põ-ÿ¥á?à -›ï[󚧟T™Ãù}Ç%8×Ý ¥Ï)·9Û:ótËýÕh·k£ßÛƒ…=Ï3‰•Á««ùŸ"» ­7ï*Á é*ó5—“ƒ™ËOåùõÛÑAÝ%§ÍGï#¯ÿ ç ¿9¡(é á(ï Ã9©‰Á ‡ Õ>é#­.ÝŸ7ϯ Ý8ã­ã½NÉÁ Ÿ'•å"ƒÙé«9å×`¯‡’õ¿ -á5— -¿1÷© í6ã% § ±M‹‡í"¿ õ/Ÿ û™Oßåë$™Ç6»Å1©¯"ý•…›#ã±&±…2õý ßÙ#Å!Ï#(¥µ#•(×"­"×õ— ƒ&ÿ»Hñ ï³7»ë$Ù éÃ#©Ë!£ Í9­2™ ñ ‰(›#ÇD×,¡#½½¥ «#•Ï"Ù-Õÿ ƒ¿0û ÷±"ƒ(±4‘ó.«9Ýí9ûÍ%Ë0ïÓ!—Û_µ?»K‹™]û1çwÉ—¢YÕ«bÃJ­˜É³ƒTí¡ƒnÁ³—ý -hk•rï!ÁX5ƒgÍIãÿtÃ(¿…‹™!Ý4™*{eï8ëå0¥Të£-ó0Ññà ×ûaé&½é3×ß‹¡a÷…-Ë(åV“U ³17õ*“&ÝÑ/ç>ã"Ñ÷ˆÉá׃Xû™¹,í£%ë!§•1÷P…ù½bÃ(ç Ç8ÝÝ1Ç«,¥"¹0·QÍ-Ï ‡4Ý «1åµ+à ó·ëCÅ ­0…Å=×»6•’‘2»6í"×#ÝPÁ_™éDý/·66Ë -Ù-…í»~Ù ¡å“ Éb¹­_Ý1å÷ íW•&é óEÉ:ë(ë“#áëJá Ý"ù'ù/Ï»&³*Ý)á ‡ ÷(Ç áEÑ3ƒrÍ××]Ź…z»‘·må!í»!ÿ÷c•}å<ƒ\û ¥WÁ —»§ó1ÏK½=ÓÙ1“… ï(·é"•í§1ïJÁMñ$¹ß%…OÅãÑÇB›“Á˯ù=ƒ«hû’“Vçùs«kß#ëp¹/­¨£Bá—Õ‹ŸX›2ûKÁ4ã1«CåGÅFÍÇß‹;ÿ?ÅAó»ë9]ÑGÍ%ù3áÃÁ"½:ù;¹ ׫:± (Ãý å#åT±"×å™NçÃÇ£<Û­™Ý"Ïaÿß)˹ »8ŸÇƒ›ã'õ Ë6¹§Ç ù+Å'ïù(³ Å÷"Çm‹L÷9çï -õ!Ý=±ë©WÓTVŸXÇDé@2çß!»+ûã"í$ÙKÙ…tñ³Ñ:­$ñ<å=Ý5•)£"óÉ+©óÝAÉ6­>·¯ãEŸKχ ¥µs3Ázã½ãcý/ƒ ‹ é:£:á'• “2¿ -ë08»Ý}¹!©­jË&ùåD…« ¡]…~÷§ íJÑ#±*íf±÷5ÿ\¿ -é4—D‰/¥PÉáÁ:ß?×ñmG» ù§"Ë%á,§-•FÙý$?¿•Û8Õb½8ƒç-•P• ½6‘å5á5½:ñ Í!/ƒo½±Å|§ˆÇ2í6×3CíñDG£6í7©.ç 1…Rýç éLá.Û …8Åq7Åå8³ ÏÝ4×Ý8勵©b­Ù@·K™ÑA©Wó·’×#/£—>ó"ã£/µ7‡› -#ÇE¿+±™ ¯­?­1ÑÇKñ ×6Ëù"Õ¡qQ%¡t¹¤õ‰U­:Å-‘>ÿñaÓšýˆߢá&+ó­…§ -õÛÑ•‹ÕŸ%ù£oé)ÏAÍAã !Ù1µ@ÕMÇß«&ù¹@ñ>9ë ÷%/¥O@#¿3·<‹A‹%/¹r-á-CÍ[ý)ór›×2ë>©ÿ.ãÍDç(§¡Ó&#ÛE·3Á[‡:Ù,«­é7Ë«7•«:±Gñ8û{“"ï¡:û=ó•%íŸG‘8á ©7… ï¥E»?¹<¡6£4Ù%ã#£ ß8å ±!›xÝ%ÇyßïRç©H­J§Ÿ‰NÁ•Ï ‹Û¡0¹ -·Hû¯çOc£ß…Lß!ÿ# -›•É4õ8Õ=Ý -éÑ!áý£F©»)ëÕ5Í7“šñv¿Ëa<ýY·¡‡¦¯<­Ã'³‰¡XÉ'“wçÑ’Ç›¥V×…£%¥¡‰õ.³nÝ©¡©ÿ)iÑ;• ½»8õ×l‹3ÕLÃSã"&Ã@¡nÛ›c“1¥­z«(£CS¥>»0DQ½]Ÿ マ]áa¥3·UŸqï—@íhË¡n­ Ó"épiÑÁ!Ã)BÃ~iÍÿoS¹AÙëA§µ×GIŸÇíAéS‰–±áAÍ)±vïáeQ·G±#Çï@ËEKûó^Qõ=Ãa•|ë>o±C‰Y‡8“u—n¹+£{ÍmQ›PÍ ówÏ­!™9™³?[Ï7ÙNç}!‰o·LŸ?Á.­O±ëE‰‰WŸ £y_±3ÿ7ÁŸël×F÷_Eá#ûVÅDQÑ*‡eÝ,±Ë™0ï!¹2kSûEW¹X¡ -½Lw›D¯9¡La—>å@S»6ßl鯧|õkµn×"…!Í… ©“·‘ƒ ÷õž•› ‹$ëoëm×7—#ÇQË”©ƒ›[íQ­Çá -ù󧡫ƒMÇÛ(±[µfZ‘-¡Vé\«©ŽÓ‹x©(‰™ŸJû7ƒŽÕÁÙƒ¿±±©³zËRt׃ë=‰P»LïÙ\Á=Ëý—&›ý8­7· ‹dÓŠÿW•#÷¹ í.ŸP‡­“ Ý ù`ï Åë?÷™É¿ãKù"Õ>…„¡ï -™<Ï"ÕE¿$¿YÅÏE££ç6#µýÉ7ÇÝ+ñõPé É Ñ#×­5“ó­¥p‡Fá=ƒÓ*Ý|‰(½tùåÕhÃéý>û ¥, µAó™Qß!§¡a¥4Ñ -éP± ùß&ñ%‰­pù·•»Ÿ/»· -‹á ×GÛ Û‰H‡VwÙ#· ßF“Ÿõ°¡Cƒ *­7©>ó9© Í%ƒ™"ש"ÍB¡™q½9—]¡"ßÏ›oÙ7‘¿$ÉX…¬åÏã«v±» Ã#³_Ù ‹½4ùqÇ0ï ­¯‹!§ÇÝlƒ„ÉB|Á(Íxõ4…"¯3Õ3û¡Õ„ñ—V•B­[•'Qã!ùJ­+åb¿(ŸP—ûfÕÕ„4ýuñMù5‹~ÁRû4ÛX6=‡”ÉÝP‡½\ï­Wí,Q½·\ÁÉxÕYÉQÁJûJÇ•… -Ía¡ •^¿&³Ç)ßV¹;ûLÙ3•a…(ùõѹ$É,éAÃ:Í …@ŸC· ‡#™ -­ë±ÿ«¡ª³õ6ó:צŒ‹ —u…\¿H-áÑyŸ*¥nå·oÿ&Ûу“žÙŒÉ Ó«ï²Ùž.ß|ÇŸõù¦­^㘃C« ͤ?¿@7Ý'ÁÓý寿¢ÏhÙ(‰ËátÓ‚‘­ -ƒÑQÙA»— …€Ã%ût¯ í4«i‰Lù½ŸQóa¡†ÛªÙKõP¡@ÅmÁ‘Tá•*ÍOÏAãÛ]›û'•$ï ÅJßh½ ƒ\—7Ç/÷aµËŠË…h‘Qù8É­>¡IéE™© ïVçë$ÁKÑË«÷@¥Uñ: -™Ha³vù7ÃM×`éÍa©ùMÅHå>rå[õµ É;³`÷ŽË¥‹Ï6ádß&Á¯…í"·Ï<—李 ¥ ƒ?U§%»!¡É9«5aí¡í!£e‘Aáï·#±£ -·ÿ*·I_Ÿ:ÿÉ`ùg³¡ýJ‹”›>Ù›q¡BÏŠQ‰ï Û~¡DÅ4…ÁTÓXË„ÕtÉ> -ãz·÷Vɤ×^£@ÛBñx«D±‚Íp‹§ÿ­Ëmµ*Ǭé -£ÿJÕ«`­ýšÍ–%Ÿ_¯Í.ñ›Ÿ§ÙX‹g/›ÿ4…SÙ Ç!ûZË&ÓïW­ ëTå Ñm©áY·>ƒx¨›5óžÍ1ù„S“†ÃÝ™r³“•‘Ë?ÿ屩d¡ Ç™Ïiý•©D­—>á@”ÉwÉù3¯ ë!×Í#ý*ý0ƒ"‘«;µñUÑNÍ=•ß Å/í» ÙA£ ÝZå*éÙ -ß‘ -à -ñlÇÉ,û9Ù'¯•@ËgÝŽÑ]‰JM³Qcóß ·Ó§{ûs³Ó:ç!±É¿c¥.ë3ù7Sï8‡•b·™ ûårá ý -µ¥níÇËÅFéÿ*ŸÅ+tõ“#“Ó ¥8í“-ç~¥¡é ±³}õ­ת‰—“eO—·óÓÙñ£÷"õ;¹³·£™ñ‡sÿ'Á`•Çƒ™cå\DÕšÅ&ãAù<ÅIû§—&µÁ6‰jã•uû:Ç'ó¢é#±F«{Ë®™צÍD=Ó`Ýy“C—2©Ñ »lá -½3›dÙ§ýQ‡.ƒ¥±oí¹ …©¡Qà ý|» ¥Bµ ÇLÿ Å· -õ—ÿ,ÁÉ ™wÙ -qãåE“)çn—Tµ¡0½@…z³ŸbËC— ¥?•q¯ˆ±xÑ…³Ë~ѯa­?ÝI»m¥"«]×DÿaÍû•HK‘8©P‹4Á8Å@™ ÍŠÑ–™“6—OÇcó‹8“.«ÕOÝdÃçëF›ÝÛ™D¥8½iõ ½p·!±@Ñšû›sÍ&í€Ó ó"žé…ñ®½9á†Í·‘¯«Õ ßn‰ -‡¹Ný¡¢å#÷ˆ*í[óUŸ)ŸF÷l¿Ž—í¥‹=¯ “jé!·W¡pÝYסÍgŸ4ñf¯ñIÁ5ÿÉ_ù÷•» W‹’«)¢± ™—¥{Å…áV±qã•£Dû$Ña‘ ×$•‰“ˆƒ&Û”‡‚½¤ÓFçDý˜ãF“Ã,ÛÝ\™¥§‘g“2Z÷ ×{¡“F÷*§%½‡×(cï ýA­>ý&ç‰fÃï?—?Õ@§(áC¹TÑß0§'ßDÑ(¯*‘‡f¡xÑ%ëjû¹…xÛ(ó©@ñ-ÅM©©Ç'‡ךчj™Û{—¯ÕNÑÑ7¡ ³Bý7ç÷™§ ý_ÍQç’õ-/Ÿ © “:å «~ó í’׋#÷¬ÅrÍ£¨‡5…3ûe‹%׳ ‡^©;•{¡Ÿ…©«³›“ ›„5¯»s¯@§SÕ+ƒ/ч­a›DÕx‰¤¯ ƒo¹=¥“Ýn©¯4±Õ¨Í9©hà Yƒ5É¥†Û©û×r‹aëÙÙσ`‡³³ï÷k¯#½§Ï ÃN“ -ÿLÙÃËálÍ©O¯Ÿ‘$™d‘¬…q‹9¹]ã6£o‘–ù‰)õ Á@ã -áIí=É=ù »çÛÙoç ›¡qÓ!ŸÅ!Ón±où9«8%Q+ñE9µ#ñ ˃C!Õ“ Û%Ó+‘#•&ƒãR¹ -‰<75«Dç'›$Ó+Ù@¿0‰ ù?q‘½"ÿ‹ ñå ½(§E7©·!í0Ç@%ÿ­M'ãñ0í3Û#ñ ¥(ÏëJ=‘9½ ùe›“ å±MŸ -§W•#‰á'£KÍ­@«3¥é;›A³ µL·0¯ ¿ùgýÃ2Ÿ?ù!»5¥Aù×+‘Që» ÇWù×T©"Õ‘)Õ—8Í ë"÷D‘4•?Ù!Ñ ÛJù/Û×ßD¿Ÿ‘…íTˇ!‰(Å%Ï`ýÝ ¯»h¹(ó‰ à -™ßR³ ßùí)Ñ­9— —»§.…"é=Ù-“#¯Ë í,—M»é ‰C%¥Õ ½*­!Û÷<½ »+ù"ï§8É0¹—¡%…ù<›ÕL¿§9›í&/í$Å6ë<¥ -­Lß*Ý­5¡!÷ï8Ÿ Á)ÃÑ+³ ›&‡ã:!Í@ó‰#ë!—@í‹%µ -ÿù"­ÉÑQŸ^áÅ4×ã¥uå¡Ñ×<‹5s·á§g»mË(©ÏR¯[ϘÕeÁEOƒý`¥4eÉ?Ý#· a÷C‰”Õ'§\Çc‘~Ù‘RÇ>ƒß/õ&ÿg‰‹õAI£ñb—ªÓ%[õ>Õ:½G×›ÿ4ý<íi¥½aé -E“½xûcíŠÏ uŸB¥VËV颓5#ãx›²½ ñ…m‰Ç^“· oÉ@Ñ…—@;¯±5E?¡;&íxűÓBÏE­!§;½¯­g¡*¯yß+»Cm£™7÷£DÑ ¿B;Á:©ë"Ï ³ƒP«'•±RÃe»=ÛÝ@ŸPËjÝe¡ÿkƒdÝT áõ>ãR¡±Ó6Ó5_§ …>ËT©I‘7»WÏ¡lí » Ÿ“é0é8W§#M‰XÓe­D‡1D¯ÿvÙÝ“ç›óo—?ù ín§ÿn?· ÇA™GÏAËA¡ß!ïA±Q…No½V½VÝ=ß4U9åaëz™kóµ8R•Ï'› -Õñå‡Ñ -ñYÅñ"Õ*½0¹@¯¿ AÝIË:ÉÓ4…¯"×¹õ £û=¹0Ý£7Ÿ¡S—‹Á“ÙhëÍ/å2û>¹)ÉÅõ+Í?¥Ý&µ—¹ÿ¯‘+»¿éb±³)¹‰ ¥Ñ‘(í¹.ù:™Ñé _‘Õƒ‹aãÉ ÁùZ‘Ç«8—)÷ý­ÓÅ Ã&Õ×ɃßUÙÉGýÕßåý×)ßZ«ÇÇ,©:—ó‹ß6Ý1Çeá™)Ûf½)­éb«³1»÷ÿK¯Û)ËûDËÙ&ÙF™'³ ­Ï‡«`÷é4“ùl_ùYÍ“sᇃ -—NW‡å ³ ñ•Zƒû+‰ƒ —]·5Çדåû瘿˅ù•QåQ ƒí'‹0‹‰D¯ŠËN¹½¥ -£Ù½n•ÃãóíY¯§ -ÿ%…#¥*å'×0õ#‘ë… ½÷·±×.³ ¿9;Ë?§Åóß?»CçÙñ:ñ¿Õ¿0Ÿ+¹½ë«8Ù¯$«×@ý­„÷áÛIû¥Íbý Ç1ŸOáÁç:áH—‡JуíïÙKµ'«¯‡G•Ù÷ó¡Û§?±EÁ¯ï åIãÕ!³ …\ɲû±¥,“Eë˜Ç;Ï·#÷ÛaíX³±*‰Ù#åKó -ÁwÅ9µ=óÃBÙ¡­W›ù9õI½#ËBÙS«ý•m±$çÑ"“&û;ýµ³!£¹©Í\ í!ßïT·FÃË -¹³TÃ&ý:åÉÍ6½ …a#ë'õ» ·Çë•ÕEÏ-±± ë û9¡(ʼn‘S© ÙÓ)íkó­"“?—1Ù(ÙÇC'á"·6Õ9Ÿ"•0á ù"=—£#Ã¥‡@Ý(ûoi ¡d‘ £ù‹§1ë?7«©‰K™ áK§‰=…™ ¿I™_¯û%“©8ñÑO™Áx± ó.‡a§!£m2×NÇdÝLÑ›³kÅ­2ñ,×`ñNÛÃ’٠ݥg‘{£Re‘Z÷O—ÓNEñÏ>ë™Ã³7ËÃg‘ã/ñ6ǻݞ¿³¿^å Ùba›9‘ …§ ïUáë’Ýã/ñ™ëy£Ñ…{û 1‡7Û£:«ù¨Á+ƒ ßšµ -•=ƒ#Á~É͉ۋ·íW« ÑŸ ó e‹ ¹9Í(¡cù;ÙMƒ ÿZÁ%•Õ’‘B‘ ÷€"Õ£7ÓÇ’“1ó6i•#½ ‹ çù;¥4¥M»˜± ᘷ é÷…u·4û©Ùvé5ûõ“Eñ8™˜× -Ï~‰'ÝH¹7í -Ÿ—!ó‘½2ùL³\áUÛ˜³ ߇ »r£7õ0å8Ë8ÙLÓÓ’¹Sùÿj›#¡lï ¥jÙ3Å(§n½cÕLÝ!Å-¡8Ë3ÑŸ}÷4¡Õï §a¿ï•¥t¹4‘#…ñ]Õ²µ{Û…}5óÛ ëí>ÇÓM½k£Ë‹›4×c¯±@í²é[‘7Å -?×ZÑZŸÛOõ?í ƒ%Ë¡4ï_I¡P·;±‹,›¥8Õ S7ÿí#»!ßiã$“[ë--ƒ*¯"¡±é$…A»Í6·7ÙJ]‡‹§Dá7õUÑJc³$Ï“>©¡ ¯8·ÿm)Ù90ç¡8›µ!‡ a©p÷ ¹$[ùl±]¯AéAù›eû#—Y¯9Á ­Û6ïAñiŸç[ñ· ¹q—Ÿ5ÁDûÙ"Å#·"¥qý|o³ c¯ñwÉaÁ…»,«tŸDûù9é7ƒn‹8‰CÏWß6ÛéSÓ±6WÅ¿S©9åbû ûSÓ?émD™/[»LÅ!£`û&ï·1ß(«2‘ Ïõó!“Q£!ÏIíbñûZÇ8ÛJ×9Ñfý1§0›&©·¤ùyÉ7G‹ ¹[¡ ß -ã g÷%›A© ݹ}÷(¹bïc«!ç;‡ÿ!Ã"ƒ°§§zg‹N×a»Á!½¥Ó ¥‰§ •§ ½‘«™aµ—µ7ù–£ÇbÁe·e… •#§"Áû?± -·5gÕ§J‰ÇÍ µJåA]³ó#ñtÓç!×wñ­ Ï9cÓ§©#·{_…moûU™ -M«“nÕlË_Sù$á;í+íx/µ‹_‡ ›£0uQï!…/û8Oã(Ç?W×$‘©ÏnÓWõÕ‡Í|Ã-™@Ë -Ý6kϽ9•/— Çv‘[ió?Ñ,¹n͈¹Ù¢Ù‘sËá ·]“‰Ý¹fiá Í8ï”ñ/ÍW“Ë ‰¢ƒ9qÅ!ß!çi¥ QùÉ#S• -É7±PÑ(·§±ƒ É»Bá8i¡ ù•·R±S­Ùmƒ —1a‹ -ï8\Áž‰ ¹…ý ‡k5‰%Ý/J• —cáBñ ã:ƒù6©£nå£ —ß#WŸmù'ÕÃç‘Ïÿ« ß’ßw£a×#á ýq¡½¹Œ­%Ý!ÑQk©²«f#Y«Kɨ·’ͱ‹i…gû£#‘ƒ É.•å•xï-é.‡­Í$³,e­÷¯§5¿0‰¯÷¢ÇÓ‡Ÿ8ã Ï ‘Å·9¥o¿°‹™‡ï7VÁÛ×7 ÷jݳ8µ ×™B›-K«LÇWå ¡Uã!™’ï -”+ï{Så;õj‡UÏ ]קƒ]…[ÍÓ6Í -Å]Ÿ[mÃ9å›l›,• m÷‡ï,õ— oaïg÷m‹×ë¥D‡DÓWŸŽÙj‘cåñõ -Ç“µó|åOÑ„ñƒMçvù2Ãé%_‘£6Ç=ß—9ß3ƒÇt¯j£Ã¥ùc¿JÛW÷žƒ‚ÿrAµ#½-٠é Ç8¡"Ï w½mé^±!Å¡™'ç£6û½„÷œû…Å oÙË¡"õS‘F©2ãÑ"kë¡’ƒy­;ó!—#K¡5Ùï#?×m¹Qá¯"¯ õ8“ Ÿ;Û`»5ó ]©Õ -M­[‘ù!û%kß7‰N©/Sÿ•«£Û‘ÉcßFK‡ ‰£˜e»{aƒA“]“©7õ…¯®Å—£Uá-džÍ«¯1¡Y½”TŸ;¹‹÷!µŸ…b³7… W…f¡ Õtcƒ ¯gÃ|¿ñï -Û ÷½&Åm_»¢Ÿ ‘lÍ!Ÿd“Z™¹?™ Ñ­ ÿq_™aÃ"çz½Û@³»6‰¡µ­“FÃ!‹ ý»°óhÝ û:]‹…« á3é:_·ƒíLד$U› ¯iû"ŸmûÓ©zUÝqÛFÕD­‰ñ -•©ûë »‡QËg™#¯"Ç)Go›#›’Ë#·"¯Œ(ƒ a½wßYë™Ùsã>½<óƒ"ï“Í6Ï;ãEU¡8« mÏ•‘½só@¿8_—‹÷š+“\k·Y·AéO÷¤»yý8QÁùyýA“7ÿ›±$}ÛÃA¹£q«ç Ù« ¹/Ç™<ÁÛ ³'±ïrý£¿™MÓÅ 1g·ß¯$±NÿŸ$¡­jÙ0ýùÃ,‡"éñ9× Ç÷“Åõ ëRõó45‘É í“ÿýCÃ6M—ËóD·"¹­ +¡› é ÿ:“«4¯lÃ1ÿŸïn‘Ãm¿7½/Ánõ–•»Oəǧ‰²¥(é|é—=ÿ!Ë.á¤ë ËWo­.ÏQ“¦bá%õa¥;õ -÷ù0÷S½Ï(û 㻣(Û(•!‹ É8ƒó•OÕ"¯p±,÷£(•ERÁW‹ÙTË—ç8‹#·.“ís¹1%«%—µS¿1å&•Ãƒ“·Z÷“\ýx»*ŸW¿‡ŸïƒË!©’ñB©aÑ~¯SÓœ½b»¡±шÍšçM¡Ÿ„¹ Åd×­ïm£tçLÓÇ…Ñ9Ý -å-ÿñ'åš3ÏŸ×&Å̓ÿ¡‘s™Œ‡qÍu­IÕmÕ<¡Ó[£Ÿnß ƒó[û7ÕÓu›¥hÿ>É©µ”ï@¤/Ãíï"iÉ­›NŸ?Ó@ý Íų:ç7µ© -™•¡ýríñ ×Ý[×6¯ Ç$Ýmµ û!‘>8­ÅW›eɵ»ß9£BóŸ>å8‹5¹>…:Ó ‘C—5¿S©³#‹Éq£"¿“s×ë''¡@óu—/•"¥på“4¿!9_?£"ùPY…¯ŇYŸjŸ ¿,¹!Ù_Ù-5¿8µ(û WÑlû韙yƒ[¿7Ç“”KË¥ƒ™kÓ•§m÷óõ…P‘!ée£BÅË’»¥‘‘^‡ ñhåŸËó0¿e±¯Ñ ×—“·f -8íY£“ -£LÙnó ñVÛ ã=ÿ é‰:ãC¡ -ÇNÉië"µñ}ï(¡ Ÿ6§P½M©7§óx¿šû Æ« ÙO·!ÍY…“5ƒMù Ó!±’É ×!•7·lÅ Ÿñ™Cµ9¥ ÿë!±× ýEï7ˆÇ$FÕ‡£9‰7‘Në8«3½NÑ#Çl§’á™K—7ëañ û,½÷`å ßaÿ §•™ -ë9ù;Ã9Ù{•Z¿#³b¿8¥<ï -‘L½5ë\Ñ m»!0ÿ Åg‹‘Sá ±W… —_ÿK« ï"ÍÃ7•?×ýS™é••¡µŒÓ0ûD‹/÷&ß«6¿Ó"ÓKƒ+³%¹#ën -ç$Q× õ½GÙå -·ó£!Á;—“—ËDÁEÿG·‹±‹ÉgÁ½$Í#ï%ý+¡½ÿ¥"Çjß" õ€Ý³ é ëï’ù@» ¯_…M™zé89’»eïA§§G÷;Ù`Í"Û‹Ÿ— -Ÿ¿“ÏK½7ç)Ñxéaï>ípÑ"çVÛ ËïZ•,Ññ©ÅqÏ"$Ó ¡é‘…&z¯¡÷6ɹA‡ §®ý˃a¿8¡jEï¤Í„¡"Ë1—é¯%Ó{í_ñC«:Ãý=ã¨Ï­w›—¡Ï_-©ÿ›ë(!ï$•Iƒ7÷3ó!¿ªËû ©H±`ç™».Ñ©ÙGaû¥+¹Ï®Óžíà -ë<ßWë³—ë,…s¡—CñW‹1™uƒ-ÃS‹OùC߉Ç]ÿŸf‰“!¹õiÿƒgåóV‹'±Í!Å)Ë5ŸlÕë¹­‰Û‘ÿ#ÁN¥‘ר·6‡Uï#«4¹}—‡4ÛPã—Ñ`Í ‡o…Ží ×Jë ¿¬ñiÁ “qÛvËÏ :¹‡Ý±¨­OïN×x©*£ïëY7ÕE£2ç&Á€Ùõ‡éj™4Ãzá–©ë;¥£]ïÅ­ÇF×W‘™·%­fÛ­·9çBݪÉnýcù{‰®¯ ƒ2Yó*á”›&Yûm¿GŨ‡ ç?ÿŸrWûM©ŸkUÃ#—o©±Q­lÁ™&Y׉ÏU€c‹J—ëoÉAˤ¿pùçû”á“'¿o‰£ói‰Íëƒ[µ&ŸóÁh›+¿~k‘KÙ²•y½R¯–¯°ïDÑIí1Ç-;í¯›:å1›±£6‰«uýz¥õ£cµ6­0Õ#OÅ¢‘E…›-ËDƒÑ)·C÷$‘ Ï‹ï—ñó”¿3¹`»tå—™„Ï5ݲ¥f©sá«5±.Ëi‹/ŸwíÏZý@/›Á¹>ïa;9£· 韓J5¥9‹Û4™3Áwé3½ -¹R×É©tÇß2…ËÝ=µ%­œ;ÃÕ“pã)•#­¥ ˵&?à ­¿9§BÇ[ûNéõR­‰w¥7—°•¨é˜·û–ï=É5§L³°«;ï -±Ñh± -µVŸˆ×‹_MŸ,Ýr»™Ý ‰ ¯híŒÏO»­õ~Ù"“.ý¬³O"óœÕSÇ« ƒY¿>‡ƒ«OñGóÃŽ—L¿ŠÍõRŸ‘xéÏMÅÝŒëg³µŠ­…¯û‰Ÿ¯vÿ¹­Eã¬Ë"ï%Ÿcç%¯6Ï8•ÝmßC± ½‡Aç\ÝLíM¹«Í]Ë7󆛖›gà Íxù ÿPÍ «”Ý5Óa™±{Ù&¥2™6‹ Ë^ýtó6‘PÅ ™$³#Ÿ³Å3¹»—9•“«›±1éŸ:«Iñ ßMÓ€·!¹ížÕoß6±k µoõá cÓ û ÝŸHQ…[ß0¹­ É -ý9{)ý «k«×hÁ -¥EÇù9¡ _•,¹!ñUù -ÿ5YƒÃ9g¿máD¹‡(÷å8ù+Ùß$§í÷—*ÉEaÿó—"á -µzÉ“µšÏ¹ñ!ÿ'cý…•Zƒÿ#‹7¥I½:1‘#écû"…o‰ -ãDý!ÿfû¡™¨Ÿ-å"ÅJË ©9ó ×@Ÿ$­"Ÿ¡(ÝP­$ó -ÿ8É%Ó ­:·9‡4Ç ƒ Õ<±@ñ$õ‰99í#éõÏ/ÓÇ)µ#ÉO×'ñƒ ïNã÷<© ûAå%¹"(û…¥×L‡"íÇ4?ñ3¯Ï ×D»+ý$ã¥6í×lûÇ -Ó'½C¡ Ã:õ ß)JÇáól¥ µå7ÛõFá« -ÛPÕ>…*¹‘ ý6¯ -é4‰?4“©)ƒ9“‹r¯± Ñ­¹8Ë%÷#ã(éå8·@µ © -éOïÝ4£>“rµ"‰E‡.Á ­Ñ&õ!¯RçhÝÝ•"ßnë— ŸJÃý!ÑPÝ«›0Ñ·¡‡XëEí‹9—•|›§«1‹Ÿû§vÇnç õ …7Í>ûLé*Û/‘"¿]× -÷ ý6ÕqÉFÙ ‡+I‡’û"Ñ#\ñ0ß]9‰dYÁ ó‹z¹!‰Ó’g“(×|á²Á]Á&›ñŸ›IÍ3Éõ ç3ŸÑ å&ÅK±Yóé åV³µ9«2óI¡+ƒ"ù‘®ù)§då¥í©±ÝO±c׋Û -“lÍ"‘*Ã]ƒ˜Ùf™m“å•6‘'ƒzÉuÃZ‹€ßEà ‘ˆÙ7ýK—yó¬÷%±Sùá&ÅÑu›÷‘%‹EÓGñS¥ ‹,©KÁyÙÉ0ƒ³2µDó‘Ë9‹‰©c¡ãWÅhå'ÏÇ 5µ§ÛA¹9ƒÁ%ñ ñ­3Ï3•5ƒ íÛ ¹*Ûœ©mÁ…™^Ýõ1sÙß&ýùçÑ7§EËEÙ ñíÅñ3×Ç|ë ¹Á'ƒ.ã Û3×óݬ“Uñ#Ÿ!ý}Á‰©"Ý… 5×!Å?»å€é¹ e©fÉD‰FÉñ9-½ªÃ9Û~»¡¯§õ© ¿6Q½ˆ»<ÃP‘‰±-áëv¯x·SÇ>« Å!Å7‰7ó<Ó>» ·‹#­D‰‡LÙO­ Û;6‘¿Q¯ Û:å)õ ½_¥;‹kóë •<ÕBŸß8åÿ©5éA‹;ã ½DÏÑçAç«ÕAµÇL¡]Õ3ÑF× 8±!¡IŸ ÑDσ*·:×3÷!ó8³9ñûGýJùO¯•#½*¿Aá—‡ »,éP­S‰“3« -ÿr¥à ÃgÇ!ëW÷xÃ"áyÛ½ ‡eÅã˜wŸx!ƒŸ©Ÿ Ã:ïŽ#Ë áŸ9Ã^Í6Åz×3N¹:³‡óÓ§ÉKï_ŸSÙ!«ù÷ÛZ­7™¹“ÃÉ7ó ïG­‘"‰0¥WƒõJù6Õ‡Ù£™U­—«H©"°í¢©“¹­‰Z“A'ÿ•&͆ÏÕ#©™$ňçk»+“z&ýˆÓ|Åo¹4œ§ãÝK× «g3·iëfÔÓ=µóvñ) Ù†½Ç&™Lëˆåç“NÛ6É -•!Ÿ· ™#…s£g—>ù·"»S¹Aå<³/¿ã}ó­*³IÉ^Õ\™y3­vå ;N— -½¥ ™¦›!½"§R8Á,õ0‹ ×Ç•ááªõ‡z÷-›¿©n¡×@É -鬳:™³çŠ¿‘ÿ 塃}¯eé ‰œ£ãiïœÛoÇ&‹8&ß{£ý ÏÛ[-¡Léoà -Ó.<—iÕßtÿq¡­b›/± -ÁSù†é'Õ~˪Ù¥6¡^™g‹[AÃGÛAý±`é8éyñLËW÷7RË ©ù‚©„1Ñ+E­i×õ4çÛS›GƒW•N™R½Q˱Mß-ñ€™6éT‘&é_Ñ Õ -×S§"ýcÅ‘]ÝWõT6…Gµ ýFõ=™(¹'¿ù#ÿ†½D—³{µƒ‹çzƒÅ­ ¯•Å<õe‡%Ùœ—F½‰›©&ÛAã)ÙŸË4ç*»‰o¡GÕA“où ù‘Ë érõŠ¹…M·!‹Ý{±Ûœý*½@ÅŒç‰ÛOßÑD§8‡2ÿNá5£u±Ï~­ÕXß3¹Då¥'í¯[³eé"ã‡uÉ‘óFµD"Õ”Ñ@ÏVÿ·#ý‹Å±«ÿ=ñ™±–±VçÏ¢©©1ß«¥Mµió0åQÉ0ñ¡™íUÑA× ×¥ çzç1Ñ™J§eÁ… ë -·@¹ŸÑ49Õ•ó]ïýlï ŸÑ+—™ƒz±=Û -ÑvóE— ß’f‡ý:™ ­ezÿ?ÍHs!³»V‘ÓCÕ6õz— Ý8 ín­Ñ8é—é™v¡…#£Œ‹#Ï •D‘¿£!“€©ç*±&ׇ&‹Ié0¡‘eí/ñÓo«#͘Çõ3· ß—³ ýÍ7±CëÕl÷6µƒ‡9ùõëwñ£!–Ó -ÏL¯ ¡oï"ß -©tý!Ïpé(ï@Á8½+ÍËç‘¥ñ3¥‘0‰&‹é½$ý%ë#•'HÕù%«£…3ÍÓ÷׫[™ãï:­Z@³~Ù/ǃ&Ïõ·³ÿ)ùPÝ&á=Ÿõ…ÍÙ¯!³ ¯RÍ0ÿ »ó­&ß=³Ã‡‹)¹ “ÇÍ ï •µ7õ9›1‰ Ó!‰é#™™ã“$“!©'é%¡0çññ ù÷Ç&É(Õ‹í å*,ùJñ³&ÉÙÝ(—ë ‰Ÿ Ÿ>© Ý!³ƒ+=ëßï%ù Á -˫˳ ¡¯ Ï{°ÿBÑ!×8*Vßçá£&‹«F@Õd¿6ÙQyÑ¥AÁ85Ÿ39Ù%+ÁA»4‹?é?9·[Õ‰å¯8)éE½ã,í3Ó Å½ë!i•9‘b5©7ÛSÃ>ÉÍ-õ/‡®½Oá­M1×8Q;ó%™:‹‹8Ýõ"ë9· -ù8×*é,»A±*‹ -¯Rí —$ß9›5ß -ó0Óá‘GÍ<Ñ£:Ã4û!Å:‹0Ñ ·4Ç(«"‰0ýƒ§ ÝJ›"‰4›#™"•Û5¹1ÛŸßa±!Ïã­ÃP¯,¿A· Ç9£ïBé0Ñ6Û0ù!ûŸ*Ñ+ë6§<ã‰B‘ óO¯çB­­!£©')t)T-Õ`-»9ñ‘7é<·“$Å -»~…ÿ ‹‘£YÉgË$Ár²•³«Z÷ƒJß Ÿ<ï‡ß2½ -í‰ÿ4‘JóeÙ4Ý-å@Ïfõ,ÝN©ÇÉ;ë:ï`¹p©z±ã§±BÍ~§Jµ\M‘\ã×|ƒñ¿ÝEç.• × Ó_Õ?ƒ%›‘TÙ½€ó„Øñ=‘ŠïqçI猓‹DA·2‡LÃë!¥6A§©ÃíBG©A‰ GÅïó ¿ÙHç)µCñÍùç(oï·¹»MÙ!³Û©0·Feñé)»;×8uõ+aÅ -§6¹*§÷+‘“ñ8û÷aÝU¡Ógí©aÍ0ÿ$ý"¿!]ïDq‹r•å8ßZ9÷6á ûF…Y×—5§[Éÿ.§—#«ÿµ?é-O!¡%Ï*¯ÿ%‹nÅ -cÝ‹Pç!C掠*ï!ó")ëÓN¹ký­( -µ ýO™+‘FmÑ6£‹,W¿A“#Á“cÃ!ë`ç¿$½AKó*%——7;íAÅÁ+Ó5Ý7sk·D­Q剋rwó “¡oë!•ƒ4—ÇMß6× ·³ åå2ÅP¡'• -á6IóF½y!õ%‘;…2£¯!¡"Ÿ¥ƒõQÉ ÿïl«Ë ¯4Õ7YÏ)³.± ‡3ýû_ŸA³9›(»"Yµ>Ù‡qi¥ó ½‡#ç¯A‰,­Xk· ™7ß%Ó#éOÕ ßŸëí&›J³ó:³§!:±#uÛ7Ç9·e·Å.Ç6«"Ç¡Á ó`ß~›?5›QÇÑ=óã#'õd±2+§c‹#7ÃÇ6Õpá!Aõ%­A7ŸW!§+WU± §^‹"‹:U/‹ñ0¹?µ;‰=;µ NÃ+eÑ ¡7ƒVWÍÝ8ÃEe™Õ!¡®Á“‘9¿˜¯ûÝP»‹‹rõUÕI£#ùk›¹Ý8ñ»gÍ -­m¿/› ¿„ƒÏR—l³™÷"¯‰TŸŒÿbÛ^ËvÕ ‰vå%‡›!¥)…Eç"›Ùxç3Á Ñ‚Ÿa¡£")ñ Ãç#õç7ÓP‹.ûy÷+ûlá¿£ É ùcÕ•AÅC¹2Ï(ñ¥ É"Ó#ù2» Å¥ª¡Žï!‹Û›•aÝ £PÃ?™ å4‡ -Ãï$‡ ‡#ù -û3<§‚£3:ó8U›h¡ ‡“ VÍ[µL,»6÷RåÕìã σ Çi“AÇ+áã(qË…ï’½ý%lj#¯cë“7˳>¹•õ5›ÕN¯ÇU‰i÷ß}ÑžÉ:Ã?› -éãÿUÉžmÇE-Ï »)Û.ñß‘8 -;‘(»I­8ë£U6‘Ù#ñN»Y“½ 3­89ùÿëÇ0ÓIãŽà É9×(Ù0±TÇËÛ -ÝQ1 -µ‰‰ ©íǦÇo3™ õó4©?í%ïX½­#ã‹õu£fÍÓ/Á«"Ýé„φ· -í$å|`/©¯»#U‰%é‚«*C‡)‘«+ý )ó í^¿!—Oï’Í?Ù$Ë¡’‡ —7™{‹8ÓÙ «^×KË— Õ$áy7© -å.•cŸ7ów“¿K³0Ó íl'Ï -ËX)©!é*ë{é¥ób9'åZÿïÅ!ù.Ÿ"ÁC× ‰Ç ÏF» ç…ÅG¥7™i¡ ÓŸš§ »;¿ ™3õ «}Ï! ù8‡xÛ7§A¹ Ó\¥ ûxÙ8ñ!—z¿‘¯9ã“9™s‘"—˜ù ç·E×.³7£¥B³[Í7“|í!ɹµ ÿE¿5ï5!×=ýݯ8ƒßyÉ¥‘Í›#íO¡!µ™&½í7¹GM•6·V…!£Pùû Ã$­bë1ãXù“÷?×çÅ.‰ûÃQƒÃé#½&ý#¡ §6Ï­Ù"õã»6Ù]ãÓgÑ"áýX‡S÷;»óPã$£?‡ ·0á7Ç>­(á/Õ9óZÏ+óÕ!É›[É&ù ³<› ëƒÙa»R«íKÅ0Ïçcç‰!g‚±™$_Á"Ç<é åÝ ÷b±HƒÝxûÓO• -ù\•"ÃýŽÇ !»6ñ˜ÍCß¹½Z™Ëgç£ ßï“)íP‘ÿ™!ùµ ‰*ùJ—.Õ ·(£ÿ›/÷J±ýi• « í!é6§ûá$Ó(ë%«*ÛKå÷:µ—$¹<ý%ÿ«0á ¹Å‘× ×+± Ã*ËHÁág‰#ÝÅùK« ÿà ¯{§¥ÍÉgËïN£ßó%ÕTç ¥#Ù -m£Uà -«*Ýn½ E…4ß%—Ù:Ñe“ ƒ:»å »$¯N±¡,‡B'ýŸ"»‹9ý"Íåó••¥ïí)¿Bû¡;¥ !Û‰J7<ƒ¹ëùý{é ËkùÉ@áÍF×M…¹½#•ïY͇Ká.C¿"£ë:“,Ã##·ñ5Á•çû7‰'û%Û‘M‘3‡4§”ÝV—;Ñ™ûIõ(ñ#ű5‰Nµ å.÷'óY¥9…V™ -áN¯3ÙN‹?ÕMÑ%·BÉÁ@ÁÅu¡.·ã"©`¥=ó ãßE£.Ç -Ÿ‘E§ ÏÁ2épó…pÕžÛí Ù›háë>Ó<Ùï1ç7¡Q¡óƒ¿«é‘aƒ­Põ-ÿ¥á?à -›ï[󚧟T™Ãù}Ç%8×Ý ¥Ï)·9Û:ótËýÕh·k£ßÛƒ…=Ï3‰•Á««ùŸ"» ­7ï*Á é*ó5—“ƒ™ËOåùõÛÑAÝ%§ÍGï#¯ÿ ç ¿9¡(é á(ï Ã9©‰Á ‡ Õ>é#­.ÝŸ7ϯ Ý8ã­ã½NÉÁ Ÿ'•å"ƒÙé«9å×`¯‡’õ¿ -á5— -¿1÷© í6ã% § ±M‹‡í"¿ õ/Ÿ û™Oßåë$™Ç6»Å1©¯"ý•…›#ã±&±…2õý ßÙ#Å!Ï#(¥µ#•(×"­"×õ— ƒ&ÿ»Hñ ï³7»ë$Ù éÃ#©Ë!£ Í9­2™ ñ ‰(›#ÇD×,¡#½½¥ «#•Ï"Ù-Õÿ ƒ¿0û ÷±"ƒ(±4‘ó.«9Ýí9ûÍ%Ë0ïÓ!—Û_µ?»K‹™]û1çwÉ—¢YÕ«bÃJ­˜É³ƒTí¡ƒnÁ³—ý -hk•rï!ÁX5ƒgÍIãÿtÃ(¿…‹™!Ý4™*{eï8ëå0¥Të£-ó0Ññà ×ûaé&½é3×ß‹¡a÷…-Ë(åV“U ³17õ*“&ÝÑ/ç>ã"Ñ÷ˆÉá׃Xû™¹,í£%ë!§•1÷P…ù½bÃ(ç Ç8ÝÝ1Ç«,¥"¹0·QÍ-Ï ‡4Ý «1åµ+à ó·ëCÅ ­0…Å=×»6•’‘2»6í"×#ÝPÁ_™éDý/·66Ë -Ù-…í»~Ù ¡å“ Éb¹­_Ý1å÷ íW•&é óEÉ:ë(ë“#áëJá Ý"ù'ù/Ï»&³*Ý)á ‡ ÷(Ç áEÑ3ƒrÍ××]Ź…z»‘·må!í»!ÿ÷c•}å<ƒ\û ¥WÁ —»§ó1ÏK½=ÓÙ1“… ï(·é"•í§1ïJÁMñ$¹ß%…OÅãÑÇB›“Á˯ù=ƒ«hû’“Vçùs«kß#ëp¹/­¨£Bá—Õ‹ŸX›2ûKÁ4ã1«CåGÅFÍÇß‹;ÿ?ÅAó»ë9]ÑGÍ%ù3áÃÁ"½:ù;¹ ׫:± (Ãý å#åT±"×å™NçÃÇ£<Û­™Ý"Ïaÿß)˹ »8ŸÇƒ›ã'õ Ë6¹§Ç ù+Å'ïù(³ Å÷"Çm‹L÷9çï -õ!Ý=±ë©WÓTVŸXÇDé@2çß!»+ûã"í$ÙKÙ…tñ³Ñ:­$ñ<å=Ý5•)£"óÉ+©óÝAÉ6­>·¯ãEŸKχ ¥µs3Ázã½ãcý/ƒ ‹ é:£:á'• “2¿ -ë08»Ý}¹!©­jË&ùåD…« ¡]…~÷§ íJÑ#±*íf±÷5ÿ\¿ -é4—D‰/¥PÉáÁ:ß?×ñmG» ù§"Ë%á,§-•FÙý$?¿•Û8Õb½8ƒç-•P• ½6‘å5á5½:ñ Í!/ƒo½±Å|§ˆÇ2í6×3CíñDG£6í7©.ç 1…Rýç éLá.Û …8Åq7Åå8³ ÏÝ4×Ý8勵©b­Ù@·K™ÑA©Wó·’×#/£—>ó"ã£/µ7‡› -#ÇE¿+±™ ¯­?­1ÑÇKñ ×6Ëù"Õ¡qQ%¡t¹¤õ‰U­:Å-‘>ÿñaÓšýˆߢá&+ó­…§ -õÛÑ•‹ÕŸ%ù£oé)ÏAÍAã !Ù1µ@ÕMÇß«&ù¹@ñ>9ë ÷%/¥O@#¿3·<‹A‹%/¹r-á-CÍ[ý)ór›×2ë>©ÿ.ãÍDç(§¡Ó&#ÛE·3Á[‡:Ù,«­é7Ë«7•«:±Gñ8û{“"ï¡:û=ó•%íŸG©7… ï¥E»?¹<¡6£4Ù%ã#£ ß8å ±!›xÝ%ÇyßïRç©H­J§Ÿ‰NÁ•Ï ‹Û¡0¹ -·Hû¯çOc£ß…Lß!ÿ# -›•É4õ8Õ=Ý -éÑ!áý£F©»)ëÕ5Í7“šñv¿Ëa<ýY·¡‡¦¯<­Ã'³‰¡XÉ'“wçÑ’Ç›¥V×…£%¥¡‰õ.³nÝ©¡©ÿ)iÑ;• ½»8õ×l‹3ÕLÃSã"&Ã@¡nÛ›c“1¥­z«(£CS¥>»0DQ½]Ÿ マ]áa¥3·UŸqï—@íhË¡n­ Ó"épiÑÁ!Ã)BÃ~iÍÿoS¹AÙëA§µ×GIŸÇíAéS‰–±áAÍ)±vïáeQ·G±#Çï@ËEKûó^Qõ=Ãa•|ë>o±C‰Y‡8“u—n¹+£{ÍmQ›PÍ ówÏ­!™9™³?[Ï7ÙNç}!‰o·LŸ?Á.­O±ëE‰‰WŸ £y_±3ÿ7ÁŸël×F÷_Eá#ûVÅDQÑ*‡eÝ,±Ë™0ï!¹2kSûEW¹X¡ -½Lw›D¯9¡La—>å@S»6ßl鯧|õkµn×"…!Í… ©“·‘ƒ ÷õž•› ‹$ëoëm×7—#ÇQË”©ƒ›[íQ­Çá -ù󧡫ƒMÇÛ(±[µfZ‘-¡Vé\«©ŽÓ‹x©(‰™ŸJû7ƒŽÕÁÙƒ¿±±©³zËRt׃ë=‰P»LïÙ\Á=Ëý—&›ý8­7· ‹dÓŠÿW•#÷¹ í.ŸP‡­“ Ý ù`ï Åë?÷™É¿ãKù"Õ>…„¡ï -™<Ï"ÕE¿$¿YÅÏE££ç6#µýÉ7ÇÝ+ñõPé É Ñ#×­5“ó­¥p‡Fá=ƒÓ*Ý|‰(½tùåÕhÃéý>û ¥, µAó™Qß!§¡a¥4Ñ -éP± ùß&ñ%‰­pù·•»Ÿ/»· -‹á ×GÛ Û‰H‡VwÙ#· ßF“Ÿõ°¡Cƒ *­7©>ó9© Í%ƒ™"ש"ÍB¡™q½9—]¡"ßÏ›oÙ7‘¿$ÉX…¬åÏã«v±» Ã#³_Ù ‹½4ùqÇ0ï ­¯‹!§ÇÝlƒ„ÉB|Á(Íxõ4…"¯3Õ3û¡Õ„ñ—V•B­[•'Qã!ùJ­+åb¿(ŸP—ûfÕÕ„4ýuñMù5‹~ÁRû4ÛX6=‡”ÉÝP‡½\ï­Wí,Q½·\ÁÉxÕYÉQÁJûJÇ•… -Ía¡ •^¿&³Ç)ßV¹;ûLÙ3•a…(ùõѹ$É,éAÃ:Í …@ŸC· ‡#™ -­ë±ÿ«¡ª³õ6ó:צŒ‹ —u…\¿H-áÑyŸ*¥nå·oÿ&Ûу“žÙŒÉ Ó«ï²Ùž.ß|ÇŸõù¦­^㘃C« ͤ?¿@7Ý'ÁÓý寿¢ÏhÙ(‰ËátÓ‚‘­ -ƒÑQÙA»— …€Ã%ût¯ í4«i‰Lù½ŸQóa¡†ÛªÙKõP¡@ÅmÁ‘Tá•*ÍOÏAãÛ]›û'•$ï ÅJßh½ ƒ\—7Ç/÷aµËŠË…h‘Qù8É­>¡IéE™© ïVçë$ÁKÑË«÷@¥Uñ: -™Ha³vù7ÃM×`éÍa©ùMÅHå>rå[õµ É;³`÷ŽË¥‹Ï6ádß&Á¯…í"·Ï<—李 ¥ ƒ?U§%»!¡É9«5aí¡í!£e‘Aáï·#±£ -·ÿ*·I_Ÿ:ÿÉ`ùg³¡ýJ‹”›>Ù›q¡BÏŠQ‰ï Û~¡DÅ4…ÁTÓXË„ÕtÉ> -ãz·÷Vɤ×^£@ÛBñx«D±‚Íp‹§ÿ­Ëmµ*Ǭé -£ÿJÕ«`­ýšÍ–%Ÿ_¯Í.ñ›Ÿ§ÙX‹g/›ÿ4…SÙ Ç!ûZË&ÓïW­ ëTå Ñm©áY·>ƒx¨›5óžÍ1ù„S“†ÃÝ™r³“•‘Ë?ÿ屩d¡ Ç™Ïiý•©D­—>á@”ÉwÉù3¯ ë!×Í#ý*ý0ƒ"‘«;µñUÑNÍ=•ß Å/í» ÙA£ ÝZå*éÙ -ß‘ -à -ñlÇÉ,û9Ù'¯•@ËgÝŽÑ]‰JM³Qcóß ·Ó§{ûs³Ó:ç!±É¿c¥.ë3ù7Sï8‡•b·™ ûårá ý -µ¥níÇËÅFéÿ*ŸÅ+tõ“#“Ó ¥8í“-ç~¥¡é ±³}õ­ת‰—“eO—·óÓÙñ£÷"õ;¹³·£™ñ‡sÿ'Á`•Çƒ™cå\DÕšÅ&ãAù<ÅIû§—&µÁ6‰jã•uû:Ç'ó¢é#±F«{Ë®™צÍD=Ó`Ýy“C—2©Ñ »lá -½3›dÙ§ýQ‡.ƒ¥±oí¹ …©¡Qà ý|» ¥Bµ ÇLÿ Å· -õ—ÿ,ÁÉ ™wÙ -qãåE“)çn—Tµ¡0½@…z³ŸbËC— ¥?•q¯ˆ±xÑ…³Ë~ѯa­?ÝI»m¥"«]×DÿaÍû•HK‘8©P‹4Á8Å@™ ÍŠÑ–™“6—OÇcó‹8“.«ÕOÝdÃçëF›ÝÛ™D¥8½iõ ½p·!±@Ñšû›sÍ&í€Ó ó"žé…ñ®½9á†Í·‘¯«Õ ßn‰ -‡¹Ný¡¢å#÷ˆ*í[óUŸ)ŸF÷l¿Ž—í¥‹=¯ “jé!·W¡pÝYסÍgŸ4ñf¯ñIÁ5ÿÉ_ù÷•» W‹’«)¢± ™—¥{Å…áV±qã•£Dû$Ña‘ ×$•‰“ˆƒ&Û”‡‚½¤ÓFçDý˜ãF“Ã,ÛÝ\™¥§‘g“2Z÷ ×{¡“F÷*§%½‡×(cï ýA­>ý&ç‰fÃï?—?Õ@§(áC¹TÑß0§'ßDÑ(¯*‘‡f¡xÑ%ëjû¹…xÛ(ó©@ñ-ÅM©©Ç'‡ךчj™Û{—¯ÕNÑÑ7¡ ³Bý7ç÷™§ ý_ÍQç’õ-/Ÿ © “:å «~ó í’׋#÷¬ÅrÍ£¨‡5…3ûe‹%׳ ‡^©;•{¡Ÿ…©«³›“ ›„5¯»s¯@§SÕ+ƒ/ч­a›DÕx‰¤¯ ƒo¹=¥“Ýn©¯4±Õ¨Í9©hà Yƒ5É¥†Û©û×r‹aëÙÙσ`‡³³ï÷k¯#½§Ï ÃN“ -ÿLÙÃËálÍ©O¯Ÿ‘$™d‘¬…q‹9¹]ã6£o‘–ù‰)õ Á@ã -áIí=É=ù »çÛÙoç ›¡qÓ!ŸÅ!Ón±où9«8%Q+ñE9µ#ñ ˃C!Õ“ Û%Ó+‘#•&ƒãR¹ -‰<75«Dç'›$Ó+Ù@¿0‰ ù?q‘½"ÿ‹ ñå ½(§E7©·!í0Ç@%ÿ­M'ãñ0í3Û#ñ ¥(ÏëJ=‘9½ ùe›“ å±MŸ -§W•#‰á'£KÍ­@«3¥é;›A³ µL·0¯ ¿ùgýÃ2Ÿ?ù!»5¥Aù×+‘Që» ÇWù×T©"Õ‘)Õ—8Í ë"÷D‘4•?Ù!Ñ ÛJù/Û×ßD¿Ÿ‘…íTˇ!‰(Å%Ï`ýÝ ¯»h¹(ó‰ à -™ßR³ ßùí)Ñ­9— —»§.…"é=Ù-“#¯Ë í,—M»é ‰C%¥Õ ½*­!Û÷<½ »+ù"ï§8É0¹—¡%…ù<›ÕL¿§9›í&/í$Å6ë<¥ -­Lß*Ý­5¡!÷ï8Ÿ Á)ÃÑ+³ ›&‡ã:!Í@ó‰#ë!—@í‹%µ -ÿù"­ÉÑQŸ^áÅ4×ã¥uå¡Ñ×<‹5s·á§g»mË(©ÏR¯[ϘÕeÁEOƒý`¥4eÉ?Ý#· a÷C‰”Õ'§\Çc‘~Ù‘RÇ>ƒß/õ&ÿg‰‹õAI£ñb—ªÓ%[õ>Õ:½G×›ÿ4ý<íi¥½aé -E“½xûcíŠÏ uŸB¥VËV颓5#ãx›²½ ñ…m‰Ç^“· oÉ@Ñ…—@;¯±5E?¡;&íxűÓBÏE­!§;½¯­g¡*¯yß+»Cm£™7÷£DÑ ¿B;Á:©ë"Ï ³ƒP«'•±RÃe»=ÛÝ@ŸPËjÝe¡ÿkƒdÝT áõ>ãR¡±Ó6Ó5_§ …>ËT©I‘7»WÏ¡lí » Ÿ“é0é8W§#M‰XÓe­D‡1D¯ÿvÙÝ“ç›óo—?ù ín§ÿn?· ÇA™GÏAËA¡ß!ïA±Q…No½V½VÝ=ß4U9åaëz™kóµ8R•Ï'› -Õñå‡Ñ -ñYÅñ"Õ*½0¹@¯¿ AÝIË:ÉÓ4…¯"×¹õ £û=¹0Ý£7Ÿ¡S—‹Á“ÙhëÍ/å2û>¹)ÉÅõ+Í?¥Ý&µ—¹ÿ¯‘+»¿éb±³)¹‰ ¥Ñ‘(í¹.ù:™Ñé _‘Õƒ‹aãÉ ÁùZ‘Ç«8—)÷ý­ÓÅ Ã&Õ×ɃßUÙÉGýÕßåý×)ßZ«ÇÇ,©:—ó‹ß6Ý1Çeá™)Ûf½)­éb«³1»÷ÿK¯Û)ËûDËÙ&ÙF™'³ ­Ï‡«`÷é4“ùl_ùYÍ“sᇃ -—NW‡å ³ ñ•Zƒû+‰ƒ —]·5Çדåû瘿˅ù•QåQ ƒí'‹0‹‰D¯ŠËN¹½¥ -£Ù½n•ÃãóíY¯§ -ÿ%…#¥*å'×0õ#‘ë… ½÷·±×.³ ¿9;Ë?§Åóß?»CçÙñ:ñ¿Õ¿0Ÿ+¹½ë«8Ù¯$«×@ý­„÷áÛIû¥Íbý Ç1ŸOáÁç:áH—‡JуíïÙKµ'«¯‡G•Ù÷ó¡Û§?±EÁ¯ï åIãÕ!³ …\ɲû±¥,“Eë˜Ç;Ï·#÷ÛaíX³±*‰Ù#åKó -ÁwÅ9µ=óÃBÙ¡­W›ù9õI½#ËBÙS«ý•m±$çÑ"“&û;ýµ³!£¹©Í\ í!ßïT·FÃË -¹³TÃ&ý:åÉÍ6½ …a#ë'õ» ·Çë•ÕEÏ-±± ë û9¡(ʼn‘S© ÙÓ)íkó­"“?—1Ù(ÙÇC'á"·6Õ9Ÿ"•0á ù"=—£#Ã¥‡@Ý(ûoi ¡d‘ £ù‹§1ë?7«©‰K™ áK§‰=…™ ¿I™_¯û%“©8ñÑO™Áx± ó.‡a§!£m2×NÇdÝLÑ›³kÅ­2ñ,×`ñNÛÃ’٠ݥg‘{£Re‘Z÷O—ÓNEñÏ>ë™Ã³7ËÃg‘ã/ñ6ǻݞ¿³¿^å Ùba›9‘ …§ ïUáë’Ýã/ñ™ëy£Ñ…{û 1‡7Û£:«ù¨Á+ƒ ßšµ -•=ƒ#Á~É͉ۋ·íW« ÑŸ ó e‹ ¹9Í(¡cù;ÙMƒ ÿZÁ%•Õ’‘B‘ ÷€"Õ£7ÓÇ’“1ó6i•#½ ‹ çù;¥4¥M»˜± ᘷ é÷…u·4û©Ùvé5ûõ“Eñ8™˜× -Ï~‰'ÝH¹7í -Ÿ—!ó‘½2ùL³\áUÛ˜³ ߇ »r£7õ0å8Ë8ÙLÓÓ’¹Sùÿj›#¡lï ¥jÙ3Å(§n½cÕLÝ!Å-¡8Ë3ÑŸ}÷4¡Õï §a¿ï•¥t¹4‘#…ñ]Õ²µ{Û…}5óÛ ëí>ÇÓM½k£Ë‹›4×c¯±@í²é[‘7Å -?×ZÑZŸÛOõ?í ƒ%Ë¡4ï_I¡P·;±‹,›¥8Õ S7ÿí#»!ßiã$“[ë--ƒ*¯"¡±é$…A»Í6·7ÙJ]‡‹§Dá7õUÑJc³$Ï“>©¡ ¯8·ÿm)Ù90ç¡8›µ!‡ a©p÷ ¹$[ùl±]¯AéAù›eû#—Y¯9Á ­Û6ïAñiŸç[ñ· ¹q—Ÿ5ÁDûÙ"Å#·"¥qý|o³ c¯ñwÉaÁ…»,«tŸDûù9‰CÏWß6ÛéSÓ±6WÅ¿S©9åbû ûSÓ?émD™/[»LÅ!£`û&ï·1ß(«2‘ Ïõó!“Q£!ÏIíbñûZÇ8ÛJ×9Ñfý1§0›&©·¤ùyÉ7G‹ ¹[¡ ß -ã g÷%›A© ݹ}÷(¹bïc«!ç;‡ÿ!Ã"ƒ°§§zg‹N×a»Á!½¥Ó ¥‰§ •§ ½‘«™aµ—µ7ù–£ÇbÁe·e… •#§"Áû?± -·5gÕ§J‰ÇÍ µJåA]³ó#ñtÓç!×wñ­ Ï9cÓ§©#·{_…moûU™ -M«“nÕlË_Sù$á;í+íx/µ‹_‡ ›£0uQï!…/û8Oã(Ç?W×$‘©ÏnÓWõÕ‡Í|Ã-™@Ë -Ý6kϽ9•/— Çv‘[ió?Ñ,¹n͈¹Ù¢Ù‘sËá ·]“‰Ý¹fiá Í8ï”ñ/ÍW“Ë ‰¢ƒ9qÅ!ß!çi¥ QùÉ#S• -É7±PÑ(·§±ƒ É»Bá8i¡ ù•·R±S­Ùmƒ —1a‹ -ï8\Áž‰ ¹…ý ‡k5‰%Ý/J• —cáBñ ã:ƒù6©£nå£ —ß#WŸmù'ÕÃç‘Ïÿ« ß’ßw£a×#á ýq¡½¹Œ­%Ý!ÑQk©²«f#Y«Kɨ·’ͱ‹i…gû£#‘ƒ É.•å•xï-é.‡­Í$³,e­÷¯§5¿0‰¯÷¢ÇÓ‡Ÿ8ã Ï ‘Å·9¥o¿°‹™‡ï7VÁÛ×7 ÷jݳ8µ ×™B›-K«LÇWå ¡Uã!™’ï -”+ï{Så;õj‡UÏ ]קƒ]…[ÍÓ6Í -Å]Ÿ[mÃ9å›l›,• m÷‡ï,õ— oaïg÷m‹×ë¥D‡DÓWŸŽÙj‘cåñõ -Ç“µó|åOÑ„ñƒMçvù2Ãé%_‘£6Ç=ß—9ß3ƒÇt¯j£Ã¥ùc¿JÛW÷žƒ‚ÿrAµ#½-٠é Ç8¡"Ï w½mé^±!Å¡™'ç£6û½„÷œû…Å oÙË¡"õS‘F©2ãÑ"kë¡’ƒy­;ó!—#K¡5Ùï#?×m¹Qá¯"¯ õ8“ Ÿ;Û`»5ó ]©Õ -M­[‘ù!û%kß7‰N©/Sÿ•«£Û‘ÉcßFK‡ ‰£˜e»{aƒA“]“©7õ…¯®Å—£Uá-¡Y½”TŸ;¹‹÷!µŸ…b³7… W…f¡ Õtcƒ ¯gÃ|¿ñï -Û ÷½&Åm_»¢Ÿ ‘lÍ!Ÿd“Z™¹?™ Ñ­ ÿq_™aÃ"çz½Û@³»6‰¡µ­“FÃ!‹ ý»°óhÝ û:]‹…« á3é:_·ƒíLד$U› ¯iû"ŸmûÓ©zUÝqÛFÕD­‰ñ -•©ûë »‡QËg™#¯"Ç)Go›#›’Ë#·"¯Œ(ƒ a½wßYë™Ùsã>½<óƒ"ï“Í6Ï;ãEU¡8« mÏ•‘½só@¿8_—‹÷š+“\k·Y·AéO÷¤»yý8QÁùyýA“7ÿ›±$}ÛÃA¹£q«ç Ù« ¹/Ç™<ÁÛ ³'±ïrý£¿™MÓÅ 1g·ß¯$±NÿŸ$¡­jÙ0ýùÃ,‡"éñ9× Ç÷“Åõ ëRõó45‘É í“ÿýCÃ6M—ËóD·"¹­ +¡› é ÿ:“«4¯lÃ1ÿŸïn‘Ãm¿7½/Ánõ–•»Oəǧ‰²¥(é|é—=ÿ!Ë.á¤ë ËWo­.ÏQ“¦bá%õa¥;õ -÷ù0÷S½Ï(û 㻣(Û(•!‹ É8ƒó•OÕ"¯p±,÷£(•ERÁW‹ÙTË—¹1%«%—µS¿1å&•Ãƒ“·Z÷“\ýx»*ŸW¿‡ŸïƒË!©’ñB©aÑ~¯SÓœ½b»¡±шÍšçM¡Ÿ„¹ Åd×­ïm£tçLÓÇ…Ñ9Ý -å-ÿñ'åš3ÏŸ×&Å̓ÿ¡‘s™Œ‡qÍu­IÕmÕ<¡Ó[£Ÿnß ƒó[û7ÕÓu›¥hÿ>É©µ”ï@¤/Ãíï"iÉ­›NŸ?Ó@ý Íų:ç7µ© -™•¡ýríñ ×Ý[×6¯ Ç$Ýmµ û!‘>8­ÅW›eɵ»ß9£BóŸ>å8‹5¹>…:Ó ‘C—5¿S©³#‹Éq£"¿“s×ë''¡@óu—/•"¥på“4¿!9_?£"ùPY…¯ŇYŸjŸ ¿,¹!Ù_Ù-5¿8µ(û WÑlû韙yƒ[¿7Ç“”KË¥ƒ™kÓ•§m÷óõ…P‘!ée£BÅË’»¥‘‘^‡ ñhåŸËó0¿e±¯Ñ ×—“·f -8íY£“ -£LÙnó ñVÛ ã=ÿ é‰:ãC¡ -ÇNÉië"µñ}ï(¡ Ÿ6§P½M©7§óx¿šû Æ« ÙO·!ÍY…“5ƒMù Ó!±’É ×!•7·lÅ Ÿñ™Cµ9¥ ÿë!±× ýEï7ˆÇ$FÕ‡£9‰7‘Në8«3½NÑ#Çl§’á™K—7ëañ û,½÷`å ßaÿ §•™ -ë9ù;Ã9Ù{•Z¿#³b¿8¥<ï -‘L½5ë\Ñ m»!0ÿ Åg‹‘Sá ±W… —_ÿK« ï"ÍÃ7•?×ýS™é••¡µŒÓ0ûD‹/÷&ß«6¿Ó"ÓKƒ+³%¹#ën -ç$Q× õ½GÙå -·ó£!Á;—“—ËDÁEÿG·‹±‹ÉgÁ½$Í#ï%ý+¡½ÿ¥"Çjß" õ€Ý³ é ëï’ù@» ¯_…M™zé89’»eïA§§G÷;Ù`Í"Û‹Ÿ— -Ÿ¿“ÏK½7ç)Ñxéaï>ípÑ"çVÛ ËïZ•,Ññ©ÅqÏ"$Ó ¡é‘…&z¯¡÷6ɹA‡ §®ý˃a¿8¡jEï¤Í„¡"Ë1—é¯%Ó{í_ñC«:Ãý=ã¨Ï­w›—¡Ï_-©ÿ›ë(!ï$•Iƒ7÷3ó!¿ªËû ©H±`ç™».Ñ©ÙGaû¥+¹Ï®Óžíà -ë<ßWë³—ë,…s¡—CñW‹1™uƒ-ÃS‹OùC߉Ç]ÿŸf‰“!¹õiÿƒgåóV‹'±Í!Å)Ë5ŸlÕë¹­‰Û‘ÿ#ÁN¥‘ר·6‡Uï#«4¹}—‡4ÛPã—Ñ`Í ‡o…Ží ×Jë ¿¬ñiÁ “qÛvËÏ :¹‡Ý±¨­OïN×x©*£ïëY7ÕE£2ç&Á€Ùõ‡éj™4Ãzá–©ë;¥£]ïÅ­ÇF×W‘™·%­fÛ­·9çBݪÉnýcù{‰®¯ ƒ2Yó*á”›&Yûm¿GŨ‡ ç?ÿŸrWûM©ŸkUÃ#—o©±Q­lÁ™&Y׉ÏU€c‹J—ëoÉAˤ¿pùçû”á“'¿o‰£ói‰Íëƒ[µ&ŸóÁh›+¿~k‘KÙ²•y½R¯–¯°ïDÑIí1Ç-;í¯›:å1›±£6‰«uýz¥õ£cµ6­0Õ#OÅ¢‘E…›-ËDƒÑ)·C÷$‘ Ï‹ï—ñó”¿3¹`»tå—™„Ï5ݲ¥f©sá«5±.Ëi‹/ŸwíÏZý@/›Á¹>ïa;9£· 韓J5¥9‹Û4™3Áwé3½ -¹R×É©tÇß2…ËÝ=µ%­œ;ÃÕ“pã)•#­¥ ˵&?à ­¿9§BÇ[ûNéõR­‰w¥7—°•¨é˜·û–ï=É5§L³°«;ï -±Ñh± -µVŸˆ×‹_MŸ,Ýr»™Ý ‰ ¯híŒÏO»­õ~Ù"“.ý¬³O"óœÕSÇ« ƒY¿>‡ƒ«OñGóÃŽ—L¿ŠÍõRŸ‘xéÏMÅÝŒëg³µŠ­…¯û‰Ÿ¯vÿ¹­Eã¬Ë"ï%Ÿcç%¯6Ï8•ÝmßC± ½‡Aç\ÝLíM¹«Í]Ë7󆛖›gà Íxù ÿPÍ «”Ý5Óa™±{Ù&¥2™6‹ Ë^ýtó6‘PÅ ™$³#Ÿ³Å3¹»—9•“«›±1éŸ:«Iñ ßMÓ€·!¹ížÕoß6±k µoõá cÓ û ÝŸHQ…[ß0¹­ É -ý9{)ý «k«×hÁ -¥EÇù9¡ _•,¹!ñUù -ÿ5YƒÃ9g¿máD¹‡(÷å8ù+Ùß$§í÷—*ÉEaÿó—"á -µzÉ“µšÏ¹ñ!ÿ'cý…•Zƒÿ#‹7¥I½:1‘#écû"…o‰ -ãDý!ÿfû¡™¨Ÿ-å"ÅJË ©9ó ×@Ÿ$­"Ÿ¡(ÝP­$ó -ÿ8É%Ó ­:·9‡4Ç ƒ Õ<±@ñ$õ‰99í#éõÏ/ÓÇ)µ#ÉO×'ñƒ ïNã÷<© ûAå%¹"(û…¥×L‡"íÇ4?ñ3¯Ï ×D»+ý$ã¥6í×lûÇ -Ó'½C¡ Ã:õ ß)JÇáól¥ µå7ÛõFá« -ÛPÕ>…*¹‘ ý6¯ -é4‰?4“©)ƒ9“‹r¯± Ñ­¹8Ë%÷#ã(éå8·@µ © -éOïÝ4£>“rµ"‰E‡.Á ­Ñ&õ!¯RçhÝÝ•"ßnë— ŸJÃý!ÑPÝ«›0Ñ·¡‡XëEí‹9—•|›§«1‹Ÿû§vÇnç õ …7Í>ûLé*Û/‘"¿]× -÷ ý6ÕqÉFÙ ‡+I‡’û"Ñ#\ñ0ß]9‰dYÁ ó‹z¹!‰Ó’g“(×|á²Á]Á&›ñŸ›IÍ3Éõ ç3ŸÑ å&ÅK±Yóé åV³µ9«2óI¡+ƒ"ù‘®ù)§då¥í©±ÝO±c׋Û -“lÍ"‘*Ã]ƒ˜Ùf™m“å•6‘'ƒzÉuÃZ‹€ßEà ‘ˆÙ7ýK—yó¬÷%±Sùá&ÅÑu›÷‘%‹EÓGñS¥ ©KÁyÙÉ0ƒ³2µDó‘Ë9‹‰©c¡ãWÅhå'ÏÇ 5µ§ÛA¹9ƒÁ%ñ ñ­3Ï3•5ƒ íÛ ¹*Ûœ©mÁ…™^Ýõ1sÙß&ýùçÑ7§EËEÙ ñíÅñ3×Ç|ë ¹Á'ƒ.ã Û3×óݬ“Uñ#Ÿ!ý}Á‰©"Ý… 5×!Å?»å€é¹ e©fÉD‰FÉñ9-½ªÃ9Û~»¡¯§õ© ¿6Q½ˆ»<ÃP‘‰±-áëv¯x·SÇ>« Å!Å7‰7ó<Ó>» ·‹#­D‰‡LÙO­ Û;6‘¿Q¯ Û:å)õ ½_¥;‹kóë •<ÕBŸß8åÿ©5éA‹;ã ½DÏÑçAç«ÕAµÇL¡]Õ3ÑF× 8±!¡IŸ ÑDσ*·:×3÷!ó8³9ñûGýJùO¯•#½*¿Aá—‡ »,éP­S‰“3« -ÿr¥à ÃgÇ!ëW÷xÃ"áyÛ½ ‡eÅã˜wŸx!ƒŸ©Ÿ Ã:ïŽ#Ë áŸ9Ã^Í6Åz×3N¹:³‡óÓ§ÉKï_ŸSÙ!«ù÷ÛZ­7™¹“ÃÉ7ó ïG­‘"‰0¥WƒõJù6Õ‡Ù£™U­—«H©"°í¢©“¹­‰Z“A'ÿ•&͆ÏÕ#©™$ňçk»+“z&ýˆÓ|Åo¹4œ§ãÝK× «g3·iëfÔÓ=µóvñ) Ù†½Ç&™Lëˆåç“NÛ6É -•!Ÿ· ™#…s£g—>ù·"»S¹Aå<³/¿ã}ó­*³IÉ^Õ\™y3­vå ;N— -½¥ ™¦›!½"§R8Á,õ0‹ ×Ç•ááªõ‡z÷-›¿©n¡×@É -鬳:™³çŠ¿‘ÿ 塃}¯eé ‰œ£ãiïœÛoÇ&‹8&ß{£ý ÏÛ[-¡Léoà -Ó.<—iÕßtÿq¡­b›/± -ÁSù†é'Õ~˪Ù¥6¡^™g‹[AÃGÛAý±`é8éyñLËW÷7RË ©ù‚©„1Ñ+E­i×õ4çÛS›GƒW•N™R½Q˱Mß-ñ€™6éT‘&é_Ñ Õ -×S§"ýcÅ‘]ÝWõT6…Gµ ýFõ=™(¹'¿ù#ÿ†½D—³{µƒ‹çzƒÅ­ ¯•Å<õe‡%Ùœ—F½‰›©&ÛAã)ÙŸË4ç*»‰o¡GÕA“où ù‘Ë érËšõŠ¹…M·!‹Ý{±Ûœý*½@ÅŒç‰ÛOßÑD§8‡2ÿNá5£u±Ï~­ÕXß3¹Då¥'í¯[³eé"ã‡uÉ‘óFµD"Õ”Ñ@ÏVÿ·#ý‹Å±«ÿ=ñ™±–±VçÏ¢©©1ß«¥Mµió0åQÉ0ñ¡™íUÑA× ×¥ çzç1Ñ™J§eÁ… ë -·@¹ŸÑ49Õ•ó]ïýlï ŸÑ+—™ƒz±=Û -ÑvóE— ß’f‡ý:™ ­ezÿ?ÍHs!³»V‘ÓCÕ6õz— Ý8 ín­Ñ8é—é™v¡…#£Œ‹#Ï •D‘¿£!“€©ç*±&ׇ&‹Ié0¡‘eí/ñÓo«#͘Çõ3· ß—³ ýÍ7±CëÕl÷6µƒ‡9ùõëwñ£!–Ó -ÏL¯ ¡oï"ß -©tý!Ïpé(ï@Á8½+ÍËç‘¥ñ3¥‘0‰&‹é½$ý%ë#•'HÕù%«£…3ÍÓ÷׫[™ãï:­Z@³~Ù/ǃ&Ïõ·³ÿ)ùPÝ&á=Ÿõ…ÍÙ¯!³ ¯RÍ0ÿ »ó­&ß=³Ã‡‹)¹ “ÇÍ ï •µ7õ9›1‰ Ó!‰é#™™ã“$“!©'é%¡0çññ ù÷Ç&É(Õ‹í å*,ùJñ³&ÉÙÝ(—ë ‰Ÿ Ÿ>© Ý!³ƒ+=ëßï%ù Á -˫˳ ¡¯ Ï{°ÿBÑ!×8*Vßçá£&‹«F@±xÑ…³Ë~Ñ“BÁm¯a­?»m¥"«]×DÿaÍû½Õ%•HK‘8©PÁ8Å@Ñ–™‹q÷ “6—OÏÓ'Çcó‹8“.«ÕOÝdÃçëF›ÝÛ™D¥8½iõ ½p·!±@ÑšûÍ&í€Ó ó"žé…ñ®½9á†Í·‘¯«Õ ùT‘%RÇœé—áoßn‰ -‡¹Ný¡¢©íQå#÷ˆ*í[óUŸ)ŸF÷l¿Ž—í¥‹=¯ “jé!·W¡pÝYסÍgŸ4ñf¯ñIÁ5ÿÉ_ù÷•» W‹’«)¢™—¥{Å…áV±qã•£Dû$Ña‘ ×$•‰“ˆƒ&áÛ”‡‚½¤ÓF;çDý˜ãF“Ã,ÛÝ\™¥§‘g“2Z÷ ×{¡“F÷*§%½‡×(cï ýA­>ý&ç‰fÃï?—?Õ@§(áC¹TÑß0§'ßDÑ(¯*‘‡f¡xÑ%ëjû¹…xÛ(ó©@ñ-™P›šÅM©©Ç'‡ךÑ™Û{—¯ÕNçWÑÑ7¡ ‹°á«³Bý7ç÷™§ ÍQç’õ-/Ÿ mÏ"© “:å «~™%ýy±SÛ!‰2á6—9ó í’“IË8׋#÷¬ÅrÍ£¨‡5…3ûe‹%׳ ‡^©;•{¡Ÿ…©«³›“ ›„5§>û÷Õ ¯»s¡E‹c¯@§S‰„Õ+ƒ/Ç!ч­a›DÕx‰¤¯ ƒoÛ¡÷ÉQù‡¹=¥“Ýn©¯4±Õ¨Í9©hà Yƒ5É¥†Û©û×r‹aëÙÙσ`‡³³ï÷k¯#½§Ï ÃN“ -ÿLÙÃËálÍ©O¯Ÿ‘$™›d‘¬…q‹9¹]ã6£o‘–÷•”ù‰)Á@ã -áIí=É=ù »çÛÙoç ›¡qÓ!ŸÅ!Ón±où9«8%Q+ñE9µ#ñ ˃C!Õ“ Û%Ó+‘#•&ƒãR¹ -‰<75«Dç'›$Ó+Ù@¿0‰ ù?q‘½"ÿ‹ ñå ½(§E7©·!í0Ç@%•Û¡"ÿ­M'ãñ0í3Û#ñ ¥(ÏëJ=‘9½ ùe›“ å±MŸ -§W•#‰á'£KÍé;›A³ µL·0¯ ¿ùgýÃ2Ÿ?ù!»5¥Aù×+‘Që» ÇWù×T©"Õ‘)Õ—8Í ë"÷D‘4•?Ù!Ë)ûCó Ñ ÛJù/Û×ßD¿Ÿ‘…íTˇ!‰(Å%Ï`ýÝ ¯»h¹(ó‰ à -™ßR³ ßùí)Ñ­9— —»§.…"é=Ù-“#¯Ë í,—M»é ‰C%¥Õ ½*­!Û÷<½ »+ù"ï§8É0¹—¡%…ù<›ÕL¿§9›í&/í$Å6ë<¥ -­Lß*Ý­5¡!÷ï8Ÿ Á)ÃÑ+³ ›&‡ã:!Í@ó‰#ë!—@í‹%µ -ÿù"­ÉÑQŸ^áÅ4×ã¥u—Û6“;gå¡Ñ×<‹5s·á§g»mË(©ÏR¯[ϘÕeÁEOƒý`¥4eÉ?Ý#· a÷C‰”Õ'§\Çc‘~Ù‘RÇ>ƒß/õ&ÿg‰‹õAI£ñb—ªÓ%[õ>Õ:½G×›ÿ4ý<íi¥½aé -E“½xûcíŠÏ uŸB¥VËVµùQç@]颓5#ãx›²½ ñ…m‰Ç^“· oÉ@Ñ…—@;¯±5E?¡;&íx¹„‰?ãã ÝcűÓBÏE­!§;½¯­g¡*¯yß+»Cm£™7÷£DÑ ë"Ï ³ƒP«'•±RÃe»=ÛÝ@ŸPËjÝe¡ÿkƒdÝT áõ>ãR¡Å„±Ó6Ó5_§ …>ËT©I‘7»WÏ¡lí » Ÿ“Ý;—«çT‘¢é0é8W§#M‰XÓe­D‡1D¯ÿvÙÝ“ç›óo—?ù ín§ÿn?· ÇA™GÏAËA¡ß!ïA±Q…No½V½VÝ=ß4U9åaëz™kóµ8R•Ï'› -Õñå‡Ñ -ñYÅñ"Õ*½0¹@¯¿ AÝIË:ÉÓ4…¯"×¹õ £û=¹0Ý£7Ÿ¡S—‹Á“ÙhëÍ/å2û>¹)ÉÅõ+Í?¥Ý&µ—¹ÿ¯‘+»¿éb±³)¹‰ ¥Ñ‘(í¹.ù:™Ñé _ñ-‘Õƒ‹aãÉ ÁùZ‘Ç«8—)÷ý­ÓÅ Ã&Õ×ɃßUÙÉGýÕßåý×)ßZ«ÇÇ,©:—ó‹ß6Ý1Çeá™)Ûf½)­éb1»÷ÿK¯Û)ËûDËÙ&ÙF™'³ ­Ï‡«`÷é4“ùl_ùYÍ“sᇃ -—NW‡å ³ ñ•Zƒû+‰ƒ —]·5Çדåû瘿˅ù•QåQ ƒí'‹0‹‰D¯ŠËN¹½¥ -£Ù½n•ÃãóíY¯§ -ÿ%…#¥*å'×0õ#‘ë… ½÷·±×.³ ¿9;Ë?§Åóß?»CçÙñ:ñ¿Õ¿0Ÿ+¹½ë«8Ù¯$«×@ý­„÷áÛIû¥Íbý Ç1ŸOáÁç:áH—‡JуíïÙKµ'«¯‡G•Ù÷ó¡Û§?±EÁ¯ï åIãÕ!³ …\ɲû±¥,“Eë˜Ç;Ï·#÷ÛaíX³±*‰Ù#åKó -ÁwÅ9µ=óÃBÙ¡­W›ù9õI½#ËBÙS«ý•m±$çÑ"“&û;ýµ³!£¹©Í\ í!ßïT·FÃË -¹³TÃ&ý:åÉÍ6½ …a#ë'õ» ·Çë•á‘W¿ÕEÏ-±± ë û9¡(Bé4ʼn‘S© ÙÓ)íkó­"“?—1Ù(ÙÇCÃ÷¹¥Ë+'á"·6Õ9Ÿ"•0á ù"=¿%¯L¹”—£#Ã¥‡@Ý(ûoi ¡d‘ £ù‹§1ë?7«©‰K™ áK§‰=…™ ¿I™_¯û%“©8ñÑO™Áx± ó.‡a§!£m2×NÇdÝLÑ›³kÅ­2ñ,×`ñNÛÃ’٠ݥg‘{£Re‘Z÷O—ÓNEñÏ>ë™Ã³7ËÃg‘ã/ñ6ǻݞ¿³¿^å Ùba›9‘ …§ ïUáë’Ýã/ñ™ëy£Ñ…{û 1‡7Û£:«ù¨Á+ƒ ßšµ -•=ƒ#Á~É͉ۋ·íW« ÑŸ ó e‹ ¹9Í(¡cù;ÙMƒ ÿZÁ%•Õ’‘B‘ ÷€"Õ£7ÓÇ’“1ó6i•#½ ‹ çù;¥4¥M»˜± ᘷ é÷…u·4û©Ùvé5ûõ“Eñ8™˜× -Ï~‰'ÝH¹7í -Ÿ—!ó‘½2ùL³\áUÛ˜³ ߇ õ0å8Ë8ÙLÓÓ’¹Sùÿj›#¡lï ¥jÙ3Å(§n½cÕLÝ!Å-¡8Ë3ÑŸ}Á0Ý8÷4¡Õï §a¿ï•¥t¹4‘#…ñ]Õ²µ{Û…}5óÛ ëí>ÇÓM½k£Ë‹›4×c¯±@í²é[‘7Å -?×ZÑZŸÛOõ?í ƒ%Ë¡4ï_I¡P·;±‹,›¥8Õ SÕ »"ýpO7ÿí#»!õAÅ…ßiã$“[Á¯¹“që--ƒ*¯"³½7› -¡±é$…A»Í6·7ÙJ]‡‹§Dá7õUÑJc³$Ï“>©¡ ¯8·ÿm)Ù90ç¡8›µ!‡ a©pÝ·9kéd÷ ¹$[ùl±]¯AéAù›eû#—Y¯9Á Õa›!å¹ -­Û6ïAñiŸ›mÕ -eç[ñ· ã»{ǯŸ å"—;¹q—Ÿ5ÁDûÙ"Å#·"¥qý|o³ c¯ñwÉaÁ…»,«tŸDûù9ýo¯SŸ‰CÏWß6ÛéSÓ±6WÅ¿S©9åbû ûSÓ?émD™/[»LÅ!£`û&ï·1ß(«2µ#‘ Ïõó!“Q£!ÏIíbñûZÇ8ÛJû‡×9Ñfý1§0›&©·¤ùyÉ7G‹ ¹[¡ ß -ã g÷%›A© ݹ}÷(¹bïc«!ç;‡ÿ!Ã"ƒ°§§zg‹N×a»Á!½¥Ó ¥‰§ •§ ½‘«™aµ—µ7ù–£ÇbÁe·e…‹T •#§"Áû?± -·5gÕ§J‰ÇÍ µJåA]³ó#ñtÓç!×wñÓ§©#·{_…moûU™ -M«“nÕlË_Sù$á;í+íx/µ‹_‡ ›£0uQï!…/û8Oã(Ç?W×$‘©ÏnÓWõÕ‡Í|Ã-™@Ë -Ý6kϽ9•/— Çv[‘[ió?ÉÑ,¹n͈¹Ù¢Ù‘sËá ·]“‰ÝÇ~¹fiá Í8ï”ñ/ÍW“Ë ‰¢ƒ9qÅ!ß!çi¥ QùÉ#S• -É7×™çU±PÕ_ƒýõ”Ñ(·§±ƒ É—0ÉRaù »Bá8i¡ ù•·R±S­Ùmƒ —1a‹ -ï8\Áž‰ ¹…ý ߧ‡k5‰%Ý/J• —cáBñ ã:ƒù6©£nå£ —ß#WŸmù'ÕÃç‘Ïÿ« ß’ßw£a×#á ýq¡½¹Œ­%Ý!ÑQk©²«f#Y«Kɨ·’ͱ‹i…gû£#‘ƒ É.•å•xï-é.‡­Í$³,e­ó5÷¯§5¿0‰¯÷¢ÇÓ‡Ÿ8ã Ï ‘Å·9¥o¿°‹™‡ï7VÁÛ×7 ÷jݳ8µ ×™B›-K«LÇWå ¡Uã!™’ï -”+ï{Så;õj‡UÏ ]קƒ]…[ÍÓ6Í -¡T·Ë8ó _Å]Ÿ[mÃ9å›l›,• m÷‡ï,õ— oaïg÷m‹×ë¥D‡DÓWŸŽÙj‘cåñõ -Ç“µó|åOÑ„ñƒMçvù2Ãé%_‘£6Ç=ß—9ß3ƒÇt¯j£Ã¥ùc¿JÛW÷žƒ‚ÿrAµ#½-٠é Ç8¡"Ï w½m…Ycé^±!Å¡™'ç£6û½„÷œû…Å oÙË¡"õS‘F©2ãÑ"kë¡’ƒy­;ó!—#K¡5Ùï#?×m¹Qá¯"¯ õ8“ Ÿ;Û`»5ó ]©Õ -M­[‘ù!û%k¿­ß7‰N©/Sÿ•«£Û‘ÉcßFK‡ ‰£˜e»{aƒA“]“©7õ…¯®Å—£Uá-¡Y½”TŸ;¹‹÷!µŸ…b³7… W…f¡ Õtcƒ ¯gÃ|¿ñï -Û ÷½&Åm_»¢Ÿ ‘lÍ!¯)Ÿd“Z™¹?™ Ñ­ ÿq_™aÃ"çz½Û@³»6‰¡µ­“FÃ!‹ ý»°óhÝ û:]‹…« á3é:_·ƒíLד$U› ¯iû"ŸmûÓ©zUÝqÛFÕD­‰ñ -•©ûë »‡QËg™#¯"Ç)Go›#›’Ë#·"¯Œ(ƒ a½wßYë™Ùsã>½<óƒ"ï“Í6ƒ(‰_ùãEU¡8« mÏ•‘½só@¿8_—‹÷š+“\k·Y·AéO÷¤»yý8QÁùyýA“7ÿ›±$}ÛÃA¹«ç Ù« ¹/Ç™<ÁÛ ³'±ïrý£¿™MÓÅ 1gçt·ß¯$±NÿŸ$¡­jÙ0ýùÃ,‡"éñ9× Ç÷“Åõ ëRõ©ó45‘É í“ÿýCÃ6M—ËóD·"¹­ +¡› ícé ÿ:“«4¯lÃ1ÿŸïn‘«Ãm¿7½/Ánõ–•»Oəǧ‰²¥(é|éÿ!Ë.á¤ë ËWo­.ÏQ“¦õa¥;õ -÷ù0÷S½Ï(û 㻣(Û(•!‹ É8ùƒó•OÕ"¯pƒ -á\·3±,÷£(•ERÁW‹ÙTË—ç8‹#·.“ís¹1%«%—µS¿1å&•Ãƒ“·ZÉU÷“\ýx»*ŸW¿‡ŸïƒË!—‰Å8«2©’ñB©aÑ~¯SÓœ½b»¡±шÍšçM¹ Ådïm£tçL©oÓÇ…Ñ9Ý -å-ÿñ'åš3ÏŸ×&Ë…Å̓õWÿ¡‘s™Œ‡q¹P« Íu­rÏ„­IÕmÕ<¡Ó[£Ÿnß ƒHó[û7ÕÓu›¥hÿ>É©µ”ï@¤‹/Ãíï"iÉ­›NŸ?Ó@ý Íų:ç7µ© -™•¡ýríñ ×Ý[×6¯ Ç$Ýmµ û!‘>8­ÅW›eɵ»ß9£BóŸ>å8‹5¹>…:Ó ‘C—5¿S©³#‹Éq£"¿“s×ë''¡@óu—/•"¥på“4¿!9_?£"ùPY…¯ŇYŸjŸ ù™"¿,¹!Ù_Ù-5¿8µ(û WÑlû韙yƒ[¿7Ç“”Ù)zK]Ñ—©Ãe Ë¥ƒ™kÓ•§m÷óõ…P‘!ée£BÅË’»¥‘‘^‡ ñhåŸËó0¿e±¯Ñ ×—“·f -8íY£“ -ÿV£LÙnó ñVÛ ã=ÿ é‰:ãC¡ -ϳ|É…|ÇNÉië"µñ}«[»"ï(¡ Ÿ6§P½M©7§óx—eáM¿šû Í Ï!Æ« ÙO·!ÍY…“5ƒMù Ó!±’É ×!•7·lÅ Ÿñ™Cµ9¥ ÿë!±× ß‹¡#ýEï7µw¿7ˆÇ$FÕ‡£9‰7«3½NÑ#Çl§’á™K—7ëañ û,½÷`å ßaÿ £v…9§•™ -ë9ù;Ã9•Z¿#³b¿8¥<ï -‘L½5ë\Ñ m»!µµ5÷uÑ:0ÿ Åg‹‘Sá ±W… —_ÿK« ï"ÍÃ7•?×ýSÑ”™é••¡µŒûD‹/÷&ß«6ý•¥¿Ó"ÓKƒ+³%¹#ën -±/¿¿ áCç$Q× õ½GÙå -·ó£!Á;—ïF“¥#³¡í@—ËDÁEÿG·‹±‹ÉgÁ½$jã!Í#ï%ý+¡ÿ¥"Çjß" õ€«_¯Z¡ ݳ é ëï’ù@» ¯_…M™zé89’»eïAëï™Å!G÷;Ù`Í"Û‹Ÿ›7ÿ— -Ÿ¿“ÏK½7ç)Ñxéaï>­z"ípÑ"+“#ýÑ9çVÛ ËÝÑ9ïZ•,Ññ©ÅqÏ"$Ó ¡é‘…&z¯¡Ét÷6ë&ɹA‡ §®ý˃a¿8¡jEï¤Í„¡"Ë1—é¯%Ó{í_ñC«:Ãý=ã¨Ï­w›—¡Ï_-©ÿ›ë(!ï$•Iƒ7÷3ëGó!¿ªËû ©H±`ç™».Ñ©ÙGaû¥+¹Ï®Óžíà -ë<ßWë³—ë,…s¡—CñW‹1™uƒ-ÃS‹OùC߉Ç]ÿŸf‰“!¹õiÿƒgåóV‹'±Í!Å)Ë5ŸlÕë¹­‰Û‘ÿ#Ís¹ÁN¥‘ר·6‡Uï#«4¹}—‡4ÛPã—Ñ`Í ‡o…Ží ×Jë ¿¬ñiÁ “q§OùN…@ëå#óï[óL¥b…²ÛvËÏ :¡’¹‡Ý±¨­OïN×x©*£ïëY7ÕE£2ç&Á€Ùõ‡éj™4Ãzá–ñ²©ë;¥£]ïÅ­Ï”µuïí>ßQÑë ‹×W‘™·%­fÛ­—‡·9çBݪÉnýcù{‰®¯ ƒ2Yó*á”Ë›&Yûm¿GŨ‡ ç?ÿŸrWûM©ŸkUÃ#—o©±Q­lÁ™&Y׉ÏU€c‹J—ëoÉAˤ¿pùçû”á“'¿o‰£ói‰Íëƒ[µ&ŸóÁh›+¿~k‘KÙ²•y½R¯–ëc¯°ïDÑIí1ÅlE§#ÕjÇ-;í¯›:å1›±£6‰«uýz¥õ£cµ6­0Õ#OÅ¢‘E…›-ËDƒÑ)·C÷$‘ Ï‹ï—ñó”¿3¹`»tå—™„Ï5ݲ¥f©sá«5±.Ëi‹/ŸwíÏZý@/›Á¹>ïa;9£ñdÑ-·-m÷%ƒ· 韓J5¥9‹Û4™3Áwé3½ -¹R¹#ûí"#×É©tÇß2…ËÝ=µ%­œ;ÃÕ“pã)•#­¥ ˵&?à ­¿9§BéõRû–ï=«;µVŸˆ×»™Ý ‰ ¯híŒÏO»­ -õ~Ù"“.ý¬³O"óœÕSÇ« ƒY¿>‡ƒ«O•]»O©•mñGóÃŽ—L¿ŠÍõRŸ‘xéÏMÅÝŒëg³µŠ­…¯û‰Ÿ¯vÿ¹­Eã¬ç%ßC± ½‡A… û ýH›gà Íxù ÿPÍ «”Ý5ë@¹ ÷ßMÓa™±{Ù&¥2™6‹ Ë^ýtó6‘PÅ ™$³#Ÿ³Å3¹»—9ÏSß í(Ûpñ ßM¹ížÕoß6±k µoõá cÓ û ÝŸHQ…[­ É -ý9{)ý «k«×hÁ -¥EÇù9¡ _•,¹!ñUù -ÿ5YƒÃ9g¿máD¹‡(÷å8ù+Ùß$§í÷—*ÉEaÿó—"á -µzɓϹñ!ÿ'cý…•Zƒÿ#‹7¥I½:1‘#écû"…o‰ -ãDý!ÿfû¡™¨Ÿ-å"ÅJË ©9ó ×@Ÿ$­"Ÿ¡(ÝP­$ó -ÿ8É%Ó ­:·9‡4Ç ƒ Õ<±@ñ$õ‰99í#éõÏ/ÓÇ)µ#ÉO×'ñƒ ïNã÷<© ûAå%¹"(û…¥×L‡"íÇ4?ñ3¯Ï ×D»+ý$ã¥6C»GÇ*Ù7í×lûÇ -Ó'½C¡ Ã:õ ß)JÇáól¥ µå7ÛõFá« -ÛPÕ>…*¹‘ ý6ÿAÛÁ›1¯ -é4‰?4Ó!ù ¹?ÕE³³7ñ8· “©)ƒ9“‹r¯± Ñ­¹8Ë%÷#ã(éå8·@µ © -éOïÝ4£>“rµ"‰E‡.Á ­Ñ&õ!¯Rí¯)ñD"çhÝÝ•"ßnë— ŸJÃý!ÑP«›0Ñ·¡‡XëEí‹9—•|›§«1‹Ÿûç õ …7Í>ûLé*‘"¿]× -÷ ý6Ù ‡+B³Ƀ -å9¡ ­‹I‡’ÍUû"Ñ#\ñ0ù&ß]9‰dÙYÁ ó‹z«?Ï@¹!‰©IÿûjùÓ’g“(×|á²Á]Á&›ñŸ›IÍ3Éõ ç3ŸÑ å&ÅK±Yóé åV韓ýÑ¿­• ë;à -±6³µ9«2óI¡+ƒ"ù‘®ù)§då¥í©±ÝO±c׋Û -“lÍ"‘*Ã]ƒ˜Ùf™m“å•6 ‘'ƒzÉuÃZ‹€ßEà ‘ˆ¥Û³Ù7ýK—y÷%±Sùá&ÅÑu›÷‘%‹EÓGñS¥ ßVÁyÙÉ0ƒ³2µDó‘Ë9‹‰©c¡ãWÅhå'ÏÇ 5µ§ÛA¹9«—õ ƒÁ%ñ ñ­3Ï3•5ƒ íÛ ¹*Ýõ1sÙß&ýùçÑ7§EËEÙ ñíÅñ3×Ç|ë ¹Á'ƒ.ã Û3×óݬ“Uñ#Ÿ!ý}Á‰©"Ý… 5×!Å?»Ñ“Šå€é¹ e©fÉD‰FÉñ9-½ªÃ9Û~»¡¯§õ© ¿6QÕA«"ï"½ˆ»<ÃP‘Õ‚!‰±-÷{á‘5Ûëv•\ÿ¯xí…·SÇ>« Å!Å7‰7ó<Ó>» ·‹#­D‰‡LÙO­ Û;6‘¿Q¯ Û:Ÿ”å)õ ½_¥;‹kóë •<ÕBŸß8‰ ·RËÿ©5éA‹;ã ½DÏÑçAç«ÕAµÇL¡]8±!¡IŸ ÑDÏ÷!ó8³9ñûGýJùO¯•#½*¿Aá—‡ »,éP­S‰“3« -ÿr¥à ÃgÇ!ëW÷xÃ"áyÛ½ ‡eÅã˜wŸx!ƒŸ©Ÿ Ã:ïŽ#Ë ¥m¡!áŸ9‰kÃ^Í6Åz×3N¹:³‡óÓ§ÉKï_ŸSÙ!«ù÷ÛZ­7™¹“ÃÉ7ó ïG­‘"‰0¥WƒõJù6Õ‡Ù£™U­—«H©"°í¢©“¹­‰Z“A'ÿ•&É™͆ÏÕ#©™$ňçk»+“z&ýˆÓ|Åo¹4œ§ãÝK× «g3·iëfÔÓ=µóvñ) Ù†½Ç&™Lëˆåç“NÛ6É -•!Ÿ· ™#…s£g—>ù·"»S¹Aå<³/¿ã}ó­*³IÉ^Õ\™y3­vå ;N— -½¥ ™¦›!½"§R8÷UïÁ,õ0‹ ×Ç•á᪹Zõ‡z÷-›¿©n¡×@É -é¬Ó1‡y³:™³çŠ¿‘ÿ 塃}¯eé ‰œ£ãiïœÛoÇ&‹8&Ãí ß{£ý ÏÛ[-¡Léoà -Ó.<—iÕßtÕfóÿq÷†¡­b›/± -ÁSù†é'Õ~˪Ù¥6¡^™gßË3‹[‡VAÃGÛAý±`é8éyñLËW÷7RË ©ù‚©„1Ñ+E­i×õ4çÛS›GƒW•N™R½Q˱Mß-ñ€…jÑ<‡v·=™6éT‘&é_Ñ Õ -×S§"ýcÅ‘]ÝWõT6…Gµ ýFõ=™(¹'¿ù#ÿ†½D—³{µƒ‹çzƒ­ ¯•‡%—FŽñ"‰›©&ÛAã)ÙŸË4»‰o¡GÕA“où ù‘Ë érõŠ¹…M·!‹Ý{±Ûœý*½@ÅŒç‰ÛOßÑD§8‡2ÿNá5£uzDZÏ~­ÕXß3¹Då¥'»cñ.‡Ná¯[³eé"ã‡uóFµD³*½y"Õ”Ñ@ÏVÿ·#ý‹Å±«ÇNÁDu‘"ÿ=±Vç©©1ß«µió0åQÉ0ñ¡íUÑA¥ çzÇÑ™J§eÁ§„ë -·@9ó]ïýlï ŸÑ+—™ƒz±=Û -ÑvóE— ß’f‡ý:™ ­ezÿ?ÍHs!³»V‘ÓCÕ6õz— Ý8 ín­Ñ8é—é™v¡…#£Œ‹#Ï •D‘¿£!“€©ç*±&ׇ&‹Ié0¡‘eí/ñÓo«#͘Çõ3· ß—³ ýÍ7±CëÕl÷6µƒ‡9ùõëwñ£!–Ó -ÏL¯ ¡oï"ß -©tý!Ïpé(ï@Á8—Wà ßß6½+ÍËç‘¥ñ3¥‘0‰&‹é½$ý%ë#•'HÕù%«£…3ÍÓ÷׫[™ãï:­Z@³~Ù/ǃ&Ïõ·³ÿ)ùPÝ&á=Ÿõ…ÍÙ¯!³ ¯RÍ0ÿ »ó­&ß=³Ã‡‹)¹ “ÇÍ ï •µ7õ9›1‰ Ó!‰é#™™ã“$“!©'é%¡0çññ ù÷Ç&É(Õ‹í å*,ùJñ³&ÉÙÝ(—ë ‰Ÿ Ÿ>© Ý!³ƒ+=ëßï%ù Á -˫˳ ¡¯ Ï{Õs»hÙ ‰°ÿBÑ!×8*Vßçá£&‹«F@™PÉ[ý7· -éMõ ù9¹5ó%ñ]íc‹D¿6ÙQyÑͬ•ãïn1õ5}¥AÁ85_'¡EÕj3Ÿ39Ù%+ÁAm»4‹?é?9·[éE½ã,í3Õ‰å¯8)Ó Å½ë!iÛSÃ>ÉÍ-•9‘b5©7ùW³D3à -õ/“~±…“×8Q;ó%½Oá­M1™:‹‹8Ýõ"û¥r“¡"Á£7û Á0ë9· -ù8×*é,»A±*‹ -3± åÿ;¯Rí —$—*… ™±#ß9›5ß -ó0­Ÿ£ ÏPÓá‘GÍ<Ñ£:Ã4û!‡±K­.ÝÝ ÇQÁ"Ç(«"‰0ýÅ:‹0Ñ ·4 ÿBõ5Í ±Ó*Û&©Aƒ§ ÝJ›"‰4›#™"•Û5¹1ÛÏã­ÃPŸßa±!ùÓ0—Dí ¯,¿A· Ç9å,Û'ѳ:ý …%ñ8»4‰ßB³ÏÝݯDá.£ïBé0Ñ6‹µ ÍA¥/Û0ù!ûŸ*‡ï[‘#Ñ+ë6§<¿ ŸM¿"ù.›%ËD½%ƒã‰B‘ óO¯çB­­!£©')t)T-É2+»ƒ9Õ`-‡_»9ñ‘7Ý7…(ù×#é<·“$Å -…»~ÿ ýy»"‹‘£YÉgË$Ár‰•³™f²ƒJ«Z÷ß Ï+¹²Ÿ–ÍqÕ;ÍŸ<ï‡ÕQí‰ß2Ëc½ -‘Jÿ4³ŸÙ4õ¦ÙpóeÝ-å@ƒ©Ïfõ,ÝN¯AÏ[©Ç{Ç‘\ÝÉ;¡zë:ï`¹pù(©z±•L»±«ã§±BÍ~§Jµ\ñMã×|ƒñ¿ÝEç.• × Ó_Õ?ƒ%›‘TÙ‘Š½€ó„Ø™ñ=ýjïq“çI猙|A·2‡LÃc·§#ÑJµ-ë!¥6A§©ÙÉe±!·NGÅïó ¿ÃíBG©A‰ Íùç(oïÙHç)µCñ³Û©0·Fe·¹»MÙ!õ+aÅ -§6¹*ñé)»;×8uÓgí©aÍ0§÷+‘“ñ8û÷aÝU¡—5§[Éÿ.ÿ$ý"¿!]ïDßZ9÷6á q‹r•å8ûF…Y×í)i‹ç §—#«ÿµ?‹&Õ™ë5Ñ;Ñ Ÿ)Ù]‹8é-O!¡%Ï*§…ë$»Gë£@¯"—"}«%ÿ_ŸK•"Ý‹Pç!Cï,Ó@]Í -Í6×ë0›aË!Á$‹Oç ¹g¯ÿ%‹nÅ -cÕ&û"£«7• 廃ùLå#»™ ½ó#ù2¥µ*ï!ó")ëÓN¹ký­( -µ ýO·³ åå2ÅP™+‘FmÑ6£‹,W¿A“#Á“cÃ!ë`¡ -BYë Ë %——7;íAç¿$½AKó*ÅÁ+Ó5Ý7s‰‹rwó “k·D­Qå¡oë!•ƒ4õ­1Å@Gù -•Uù%‡m§7£-©:—ÇMß6× ß%Ó#éOÕ ¡'• -á6IóF½y!õ%‘;õ ÿ{¥]ÿ ñ8e“>­/× ±$‰M7¡ßA™Y•7 -¿*ç@Yé ƒ=Á)aà -±6Í*éO©&ŸV¯•W¿í¥ óÏ -•!—§ÿ?­,ÑÛ “áï#©eÉm…2£¯!¡"Ÿ¥ƒõQÉ Ë*‰µ·ûJÿïl«Ë ¯4Õ7Y½Íc‘@™6Ï)³.± ‡3ý»' {ÝNë û_ŸA³9›(»"Yµ>Ù‡qi¥ó ½‡#ç¯A‰,­Xk· ™7ù*§*ÿU ߟëí&›J³ó:³§!:·e·Å.Ç6±#uÛ7Ç9«"Ç¡Á ó`›?5›QÇë—± -gU/ý£¦­OY­)=]UýyÑ=óã#'õd±2+§c‘;“?MÇ6‹#7ÃÇ6Õpá!Aõ%­A7ŸW!§+WU± ‹:U/‹ñ0¹?µ;‹"¯ûÝP»"Á“‘9¿>ë8ãõVåÃ+eÑ ¡7‰=;µ NµsYÁ×*¥ ËÿmÍÝ8ƒVWÃEe™Õ!×›GÏ »‹‹rõUµ ÕIùŸ£#›ùk‰:‘¹Ý8ñ;ñÍ -»g¿/­m©›› ¿„÷"ƒ¹m—lÏR³™|ý‰¯‰TŸŒ¿tÛ^ÿbÕ Ëv‰vå%¡‡›!¥)…E± -·›Á §&Ç„Óí\óG›^ñ ÷§§ˆŸa¡“‘‹.ñKõç7ÓP£ É «+Ï8Õ•ß|óy÷+û‘C£5ûlá¿Y·%³e¹—=7ãOÙ ¥ ¡#¹2Ï(ñÉ"Ó#ù2©'³6‹bÅ¥ª¡Žï!å4©Ã?™ ‹Û›Ù••aÝ £‡>×gU›h¡ ‡<ù -û3©%õ‡ -Ãï$‡ ‡#£3:ó8·Oé” n—û;¡=ñ!£ ‰…Ï Ë>“ VÍ[µLÿ3,»6÷RåÕìã Ï·sÇi‹ã0“AÇ+áã(qéË…¥ Ë&óf]lj#á<Ýaý%Á#DZë“7Ëó8Áõ5›ÕN¯ÇU‰i÷ß}ÑžçlmÇE-Ï É:Ã?› -é¹4ãÿUÉž»)Û.ñß‘8 -;‘(»I­8 3­89ë£U6‘Ù#ñN»Y“½ÿëÇ0ÓIùß×7…\à É9×(Ù0㎱TÇËÛ -© ¿ÝQ1 -µ‰‰ ©íÇo3™ õó4ǦïX½­#©?í%͇©¿ßã‹Ó“õu£fÍÓ/ÁÓÙ «^Ýé„«"1©2í$å|φ· -«+ý )ó `/©U‰%¯»#‡ˆ·!±ÝPŸ £é‚«*C‡)‘—Oï’í^¿!Í?Ù$™{‹8Ë¡’‡ —7íZ« ‹ÃNów© -å.£8Ño· Õ$áy7×KË— ë ï"iÑ9õnÙ•cŸ7ýT¯³0Ó “¿KûnÁ ËX)©!íl'Ï -é*ë{›oµ"饋Xå!OåZÿïób9'Ù1÷Å!³aƒ:ý ·Oÿó#ïµífï"ÛÇ7Ÿš§ ‰Ç ù.Ÿ"ÁC× ÉrŸ6ÅG¥7ÏF» ç…™i¡ Ó»;¿ ™3õ «}Ï!ûxÙ8 ù8§A¹ ‡xÛ7Ó\¥ ñ!—z¿‘¯9ã“9µZ—&—˜ù ™s‘"ƒ+Ùz×.³7ç·E³[Í7£¥B¹µ “|í!É¿9ÿ ÿE¿5×=ýï5!ƒßyݯ8íO¡!Í›#É¥‘½í7µ™&¹GM•6·V…!£Pù͵}û Ã$­bë1ãXù“÷?×çÅ.‰û¿;Å í— ûÃQƒÃ…åã÷BÝ$Ñ"á½&ý#¡ §6¿7‹0÷3©3› Ù"õã»6ç(ã$‘,“‡ ·0‡÷P™÷;»á7ç­(á/ƒ¯D¯4ûÓ• -‰Eñ•"ÃÕ9Ÿ!Ï+óÕ![É&ù £8ëƒÏÿ«"Ç !»6ï)ùùLõ ûÃ*“Éå"§'‡B…#‡Ó#¥ó,½3Ï&‹ÑÍ+±#¡ É"ÿ.™¥B§%ç£ Ýƒ!›+á+ß!ßï“)Á­5¹(‘1± ‰)¿&ÿ™!ùµ ÏA£ç$ùJ—.Õ £•k›/÷J±ÍY• « ¥YÇí!é6ÍCß¹ -ûá$Ó(ë%‘«*±!å÷:‹µB­6ËÕµã¹<ý%ÿßGå"™¹‹«0á ¹§× ×+± Ã*§"Á‹7×0‰#ݽ ¯×­ ½8á·1Ç0ó,ùK« ÿ¥Ÿ ã÷ía­©› ëƒ-­a«‘5ÝÅ0Ïç‰!ù/‰7±™$¹V×Á"é åûc÷b§¥Í™0±7Áå"ÍÍ0­Ë¥>£ßó%ÕTç ¥#Ù -m«£U‘mà -\ñ0ù&*Ýn½ E…4ß%—Ù:å »$¯N±Ñe“ ƒ:»ý¥û1'»‹9•ý"É€Íå» ó•¥ïí)¿Bû¡;¥ !Û‰J7<ƒ³£'§7¹ëùÏ:ý{é ùÉ@‹×£Z£÷É(ɱ:ŸB‹ çû7‰'½ÍF‹…¹½#‡Ká.C¿"•ïYÍ£ë:“,Ã##·ñ5¥Ï)·9Û:±!û%‘3Á Ç*Ã<ÿGÛ‘M¿¯'ÝVË=Ã3—;³Ñ™Ÿz¡§B­hû2›±+·dûIµ®õ(ñ#ű5É%¯Ímµ å.U£'™ -áN÷ -óY¥9…VÉ&¯3áë>Ó<ÙéxåvùH½fÙN ‹¿!׋?ÕMÑ%¡.·ã"“9Åu·BÉÁ@Á Í‘¥=ó ©`ãßE£.© µ6§ ¹3ÏGÇ -Ÿ‘E§ ÏÁ2ép!ÕžÛ»¹9ÿAó…pí Ù›há?à -›ÃU­ï1ç7¡Q¡óƒ¿«éñE‘aÉ0å8ƒ­Põ-ÿáz§ù?ÕF™Ãù}óç’õÇ%8ëÛ&×Ý …=ËótýÕh£·k»ÛƒßÏ3Ñ™Á‰•««ùŸ"» ­7“ƒ™ËOåï*Á é*ó5—Å0õ!ß$‰ÙÁ ‡ Õ>é#­.ùõÛÑAÝ%§ÍGï#¯ÿ ç ¿9¡(é á(ï Ã9©‰ÝŸ7ϯ Ý8Áß#‰3½#£ã­ã½NÉÁ i»x¯‡’Ÿ'•å"ƒÙé«9å×`ç C­5¯‹"õ¿ -á5— -¿1ññ…8ß ß2ßÙ#Å!Ï#(÷© í6ã% § ±M‹‡í"ßåë$™Ç6¿ õ/Ÿ û™O»Å1©¯"ýï)¹ƒ8Ã8•…›#ã±&·ƒ4ï'¹ã ±…2õý ™ Ë)ÝŸ;»ë$Ù éÃ#¥µ#•(×"­"‘ƒ#Ñé;‰1×õ— ƒ&ÿ»Hñ ï³7Õ½!û;Ùé Ý3×"Ëí ÷"™ ñ ‰(›#ÇD©Ë!£ Í9­2›Ó#Ó“"™«8« »5Ë -Õÿ ƒ¿0û ×,¡#½½ýÏ$¿Û ý"» -ƒ‰‡6£+¥ «#•Ï"Ù-÷±"ƒ(±4ÙÅã -¹6÷ãÅ9ã¹6Ó '— -ã:Û%»› ñ:«2«™ ‘ó.«9Ýí9ïÝ Ë7Ñ ƒ1Ÿ· ÕMß ý …5Ó#ù"Ç Ÿ‘,ï £6åûÍ%Ë0ïÓ!Û_ߟ&»Kû1çw‹™]…No¿½V·‰7‡ -oÍ -ëaÕ«bË1Õ -Y‡8ÍÇ¿ -é4—D‰/áà ‹o­$ÅAó»ë9ß‹;ÿ?]ÑGÍ%¹§Ç ù+(Ãý å#׫:± ù3áËÅW÷Ç!Á"½:ù;¹ ƒƒ…©‡ µ!éRÕ'õ3ç"Ý!×­¿‹7Ù.Ý"ÏaÿåT±"×Ç@—½ -å™NçÃÇ£<é4±QóÛ­™ß)˹ »8ŸÇƒ›ã'õ Ë6ù,·fÅ'ïù(³ Å÷"Çm‹L÷9çï -±ëõ!Ý=VŸX©WÓTÇ ÏeÇDé@2çß!»+ûã"í$ÙKñ<å=Ý5Ù…tññ+#Ñß³Ñ:­$é:£:á'•)£"óÉ+©óÝAÉ6­>·¯ãEŸKχ ¥µsÁz3ã½ãcý/ƒ ‹ û @ë08»«Ù ç• “2¿ -· “ç Ÿ™©§ íJÑ#Ý}¹!©­jË&ùåD…³G¡)« ¡]$­p£áeí7ý ÿ ÕM…~÷±÷5ÿ\±*íf¥Pù§"Ë%×ñmG» ÉáÁ:ß?åÁ{×é ßm§ý$?¿•Û8á,§-•FÙÅå8³ ÷>ñ Í!/ƒoÕb½8ƒ½6‘å5á5ç-•P• ý`½:­¥­˜ÃJ½±Å|§ˆ‹GÉíñDG£6Ç2í6×3C³…Rýçí7©.ç 1ƒT …8Åq7 éLá.Û½‰Ç×h/Ã*ÏÝ4×Ý8ÇéxÙ@·K™å‹÷bç -µ©b­ÿ5©ñDËù"Õ¡qQÑA©Wó±÷C·’×#/£—>ó"±™ ¯­?­1ã£/µ7¹)Ý ÷6)ç@«7É—?‡› -#ÇE¿+ÑÇKñ ×6eµ){Ë ÷hkŸ ï!ƒnÁñ'ý -»[·!ÍIãÕÁX5»Dó}Ë€ÃñUIå2­ ¡t%Ã(¿ÿG‡™!• É\çÑ.‹Q¡‘ ëå0¥Tëñà ×&û;¹¤£-ó0Ñõé&½é3×…-Ë(åVß‹¡a÷­:‡…=Ù ãç ÿ4›¡§6ƒ(Ý3ýÿ9ß0Å(‘)¯a› •í0‘ÏÿO§/­<ñ!Û½ §¡g“U ³1•¹,í£%ë!7õ*“&Ý•+åx׃Xû™Ñ/ç>ã"Ñ÷ˆÉá‹>•)٠ó-µ!ƒ'õù½bÃ(ç §•1÷P…Ç8ÝÝ1Ç«,¥"¹0ó ÿ\ß5×Ëx½ -ñ7Ï··QÍ-Ï ‡4Ý «1åµ+à ó·™VÓ.Ÿ¿!ûm‡« Ý2¹6ëCÅ ­0£‹›E×0‡£)‰Ù¯$á¿…Å=×»6ïY¹‹4•’‘2»6í"×#ÝP… ›2ÛK™­™,“ ßÁ_™á\Å…4í»~Ù ¡éDý/·66Ë -Ù-…½ ©å\¯(õñ3¡Véõ8• Å3õƒ/‰9µ=‡É½`­ÁÅ)§Lï¹­_Ý1å“ Ã‰bå}÷ íW•&“£,×Ó·Pß.ñOå'Ã(ƒé óEÉ:ë(íûQ±1 ë“#áëJÏ¥4õ×\á Ý"ù'ÿ"Õ4™³ÝGõ¹"Ÿ(¹Õaÿù/Ï»&³*›T¡1¡ÿÝ)á ‡ ÷(¥ -Ÿ £ ½¥+…V×,ÝQ½¿Wé3ßÇ áEÑ3÷Låé™(ƒrÏ÷…Õ+›%åãUÑ ­†Å-ÿ‘>‹ýˆñaÓš+ߢá&ÛÑ•‹Õó­…§ -õÕMÇß«&Ÿ%ù£oé)ÏAÍAã !Ù1µ@ë ÷%/¥ù¹@ñ>9ó -Ã%••ló$Ï¿n/O@#¿3·<‹A‹%/ƒWí“;É3ç÷-ÑDCÍ[¹r-á-×2ë>©ÿ.ý)ór›¡Ó&#ÛEãÍDç(§ÑE£Å(/çÉ ¥Iå Á —§“…åó#É9Ÿ “±}»2« -ƒ\û åx§û ï—ï(·é"Ù,åÓÙ1“»§§,ÍÏKñ*å#ïZ…tÝ’•í§1ó)ý ‹2Õ8݇ -Ýñ¥é7ß -›“ëP…OÅåÿÑ«—Kñ$¹ß%ßË«7•#+±xÛ}÷©Í*û{“"•«:±Gñ8ï¡Sÿ)ÓKiã ©Í'³nÝÇK£‹ÿR¹>‰káŒÕ!íÝ© _ß»8Ã>‹"³ñÅ;cõ—*ÁB‡ç‘í¿0·4…ŒŸƒ ãõƒmå1ÃSÏ&‹Kƒ2ËYý§7Ã)BÃ@¡nÛ¥wc“1ÃG£CS¥>«(Ñ‹õvmµ—,…kCç»0ƒ-›QµAoõ“7§3ïÉ Uû2¥>ãÿ^¥3á ]¥ßƒÕíhµ— —Ó"ñnùiáéS‰–µ×GIÕOÿÃ~iÍÿoS¹Aµ|U¡ÙëA§ŸÇíAû £nc±áAÍ)±vïËEKûáeQ·Gß‘kÉáA-±#Çï@‰Y‡8ó^Qõ=Ãa•|½xKÙë>o±C!™9™×©ƒ ïï.“u³"åK¿/›PÍ çQÙ›aÏ­Óýbÿ!eÇÏ7å[›F‘•W£ ³Lµ1…U© ©ßyÁ.÷›/…‰oû¿(Ãi³é±Ù?“‰…ƒk½"Ë[¿+·!Õ1gõ›¡u׳+·\c…£2ÿ7‘_£^©Mõ • Ý,½õ˱ á—_õ&ÁŸù0ó;Ñ*«,Ý8é Q»T«Kû "—>å@S…ñA ûEW¹2kS½Lw›D¹X¡ -Á!I×A¯9¡LaÙí&ÑgŸõkù…!¹I¯(›TÅé‹$áI×75o“»… ©Ñaƒ ÷› ¿Š:ûó•%¥E»?íŸG‘8á ©7… ï£4Ù%¹<¡6…+Ý"ç©H­Jã#£ ß8¯ ãDå ±!›x‘Ã7ùqÝ%ÇyßïR‘‹§Ÿ‰NÁ•Ï ‹Û¡0¹ -Å ‰› ¥Çx·Hû¯çOc -›•É4õ8£ß…Lß!ÿ#ç…¡PÕ%ÇÇ¡"Õ=Ý -éÑ!áý£F©»)ëÕ5Í7Ë'Ÿ ëLÁƒçH˯ù=«hû’×c“VçÉC¹/× ¿¡ùs›&«kÇ Ëa¡­¨׆Õ‹á—£BýY·¡‡“w¦­¯<Ã'ŸAÏC•4¡X³‰Åf‘‡É'›2ûK³ç¹DÅR@ÅFáZã1Ã$££ ù4½5_Ã/«C­B£%Ã"½ï Á4ÉXåI‹1ç=ÑoÍ×¹…zƒ³ÕŽ¿•_‘MÅ “P­‡ª×]űpé9»‘ÓLѯÓA— ‡ží»!·må!ÿ]©ÿ÷c•ó 1÷%—#±.©ƒ£Q­ãåá -ùõÿ§¡ƒM«ÇÛ(ǵf±[É…Z‘-¡Vé\«ÿ£x‘’§M©ŽÓ‹¹I½r©(¿8)뉙ŸJû7ƒŽÕÁÙƒƒe‰0¿‹¿±ƒ)ó%±©Å£³FÅ~³z…LËRë=t׃‰P»LÇ‚»qïÙ\Á=Ëý—&›ý8· ‹d“­7…8ãI§ÿW•#÷¹ í.ŸP“ Ý ù`ï ‡­‡&¹±O…&Ïë?÷™ÉÅ¿ãKù"…„¡ï -Ã8áÇù!Õ>Ý`§+ÝP‘•Í%³± -™<Ï"ÕE­ ¯ËA¿$Å¿YÏE££×-ÕFÝ …œç6#µé‡=ýÉ7ÇÝ+ñõPé ¯fé û7É Ñ#×­5“ó­¥p¯û¿ ‡Fá=ƒ‰(½tùÓ*Ý|åÕhÃé¯ µ7—5ý>û ¥, µAó™Qß!§éP± ùß&¡a¥4Ñ -ñ%‰­pù»· -‹á ·•»Ÿ/±§N± ×GwÙ#· Û Û‰H‡Võ°ßF“Ÿ¡Cƒ *­7û4Á)§¥(“& «á?—]¡"ß©>ó9ƒ®© Í%ƒ™"ש"ÍB¡™q½9Ÿ{ó"£—Ï›oÙ7‘¿$ÉX—åÏã«v…¬±» Ã#ïÇ0ï ­¯³_Ù ‹½4ùq‹!§ÇÝl½Õ^Ñ ­…?Å7Ù"ƒ„ÉB|Á(Íx…Ý&»%íIÝ‘fõ4…"¯3Õ3û«Ué Ó%Õ„¡ÅT•B­[ñ—V•'Q½1«jã!ùJ­+åb4ýu—ûf×SµJ¿(ŸPÕÕ„5‹~ñMùÛX6ÁRû4‡”=…×PÉÝPï­W‡½\í,Q½·\»Q‰>Ç•ÕYÉQÁÉxÁJûJ¡ •^… -Íaß©Q׳õ>íPƒ<§g¿&³Ç)ßV¹;ûLÙ3•aŸC· ‡#™ -…(ùõѹ$É,éAÃ:Í …@­Ÿ*ñˆí;¹2ó:Å4å‘.ÿ&Ù¡­µ-Û?Û³w¯=«hу»-·~ÿ«ë±ño…\Õ0—uý(É ÷'¡ªÑy‰%õ‰á1.ß|ÇŸ•õͤ?­^ƒC« ã˜ýå¿@7Ý'ÓÁ¯›;ù¦ÍkÍj˧ãuÃ%ût¯ ‰Lù«ií4¡R½ŸQóaËÏhÙ(¿¢‰Ó‚átÙKõP•$ï ÅJ¡@“ ³Mó(—©_¯Qµ;Û]›û'Á‘Tá•*‡»LÍOÏAãßh½ Ñ˃\—7é5õÇ/÷aË …]µÃt‰‘Qù8¡IéEÉ­>™© ë$ÁKïVç -™H9(¥Uñ:«÷@³vù7Ï6õ×`éÍa©ùMÅHÏ"µå[õå>rµ É;åÅÛªçß&Ã_»?§(­ -‘ƒÑQÙA…€»— Õ/Ñçñ9‹5sáÅ4×ãÉËq÷¯Qÿù"­É³#Ÿ.ß· Ñ»s­Ñ%c¹AÛ.çûÛ*k©-—Û6“;gý ù5“å+WÏ9é>iå µb¥áë ½[»m©ÏR¯[ÑÕeÁEOÝ#· a÷C¡ƒÇ%·;¥4eÛ YÃ.·Q‰g±"³,•+«Í9û:ÓÓ%[‘!åÕ:Õ'½VëÇcÙ‡.‹$Ç>ƒƒUé«A åõ&ÿg±/õAI£¹Y¹ Ï uŸBë»O3‹9¹ ŸV×›ÿ4ÿÿ#¥½aé -Eë1Uù5Ç4“½xŸ Ý c…-ûPó¥Y™jÅ(µùQç@]“5#ãx×颽 ñ›Në‰Ñ…—@;“· oÉ@¯ó&¿E?ÕÑn ñ8·ÿ*·I_…í"·Ï<—李 ¥ ÑÅ7ÏJ]Ù;‹M™ƒ?U§%»!¡%§\Ë© ãM£WÏ8· ¡É9«5aí¡í!£e‘A‰#¥+[­"áï·#±£ -Ÿ:鱂Ÿ¹6ãÿk¿×÷.ͱ^…Õ…a—¡B³?‰ÅláJ¿2ï Û~Ãߣ ß8Å4ÁT‹…û¦ÿ½­©QŸË„ý'çT§ É`µ*Ÿ.¥l·)·GçK%Ýbé -íiÁ¤ùp£§* -ÿJå/Õã÷Vµ Í.¥J­çmã$Å ç’×^§<£@«V%ùBÛBů…£?«DÇWQ§åŒŸß2ïW­ ·+ÙX³/›ÿ4Ù ­2›^!ûZË&ÓëTå Ñm­¬©áYå^·>ƒxÙ}¨‹ ùq¯œ›5óžzÍ1ù„S“†ÃÝ™r³“íD•‘Ë?ÿ屡 Ç™Ïi©dõ"éåjý•Éù3¯ ë!©D­—>á@”Éwã%‘«;µñU×Í#ý*ý0ƒ"•ÑNÍ=‘ -à -ñlÇß Å/í» ÙA£ ÝZå*éÙ -߯•@Ëgý?—2Å?É,û9Ù'ÝŽM³Qcóß ‰JÑ]É7§{“2Ó×z·‰Zó¡'³à ‘1ç!'Šårá Ë Ñe•]‡ ¡ñ/ý -¹šËÅFé‹ íÇà Ÿ“#“¡³¥8í¿"õ“-ç~¿¡é ±³}——õ­¥.›5ç!Á®‹‹ת‰——·óÓÙ« Oñ£ã"¥³·£¿­¯ -÷*ûKÅB• ù¡ÕÍÅß!ÃD—“]%á/ý Éë3ù7Sï8‡•b·™ û£,™>2ÙñåïSÑj­/Ï5› ËAãÛIáUË -½Xo“ ‹ -»8ÛEµ3çà …T­D§Û¹QÍLó=¥»$Ïi‰¿Z¯šÇ …2g¿/Û$[ÓõóP—7¯C­-«ûá ©"§©Mg¹:볓<õS“ïSõû4½ó#Á`‡$•Çïï_µ¿;íQ“ƒNýÝ ýŸÁ¹!ñ¯—l•å\D -ù÷߇Å&—4Í á)™áÅI•,ù§ë -ó ¥µ—­•ý‰0…5ãÃFƒÑ&û:ûÍ­ÑÍ»!¿]Å•¹ÕŸ/çŠÉ ÍçJãN͆§Ï»› é#ÛC×ñëWÁ#÷xÃ"“™½€›&…©™N‰±1=í™$Ï6ÍDÑ ÙãSÝyý)“C‡—2—e©ƒ@á -½3©J¯(‰_«›dÍýQ»+ÍÇwÉ ¥ëÇP·8Ó|ñ0×Qñ%¹ å¤ã Åà ý|¯» ¥B¯Mµ ÇL­5· -ý>ùXÙ -Án3«ÿ,Á‹É O(ãåEç!å ;“)‹%— -½‹,¥ çFµÿF½"ÉW³›!‡½@å+ýå$§RùËC¿‘שía— ½'å¡Ím·ý±x¯ˆÁ,õ0û‘ 68¿FÑ“BåïïW×åP¥"¿"ÝI«]·"¡"ÿa©,Íû›½Õ%©õ‡“+‘8ë•H©PÉsÇ÷!c·‚ëû‡/ó‹4Á8× Ó ÍŠ×ý -ó"‡™g¹/™ßË3ã$÷ ¯›û#·)›ñI7ÓVí“6ù$Ÿ*­~‰ó -ÏÓ'ç(›8Õƒ:é÷ ™4»é…|‹8Ñ ýÇëDAÇ"ó‹I÷Pá ¹ ›íK]•"Û£L«¿—1µ$ëƒÝd·±-¡.§ ÃÁ ókç‹<á -ëL›Ý$R•2Å«ŸWÛË Ï6¥8©•Mõ ½p·‡ !±@Ý"1Ñ+טû›sµl‘¯õO­4Í&Á­bóC—>£ÓÇI£á õ-Õ…¥"ÑíJ@Ûj½—½9­L™ñÍ•wù%Õ ã‡ùé+õIË7†áo‰(߃!§Ë‘%-Ýßn‰ -á1—[‡÷½6éS¥ƒ-Ÿ;å#©á1‹-íQ½/Ÿ)Õ…“ É.‰RÃ#—Ÿ—ù±p¯—ï4·W§Å·1¯ »£‰-ó3‰T¯ñ+Ó2]¡§N÷‰*ã‹:Ç“Që§.ËÿPÑÏG¥«/ÿÃ3±ÙãKùÃÇI÷>‹¡åh–± õZõõ -áVÑ•Ÿ‘ 멯×$¿dƒ&‘bÁIÉIᡇlÕÓFë]¹EÉ%;TÓ$…8Í'³yçD—T)·HãF«LÃ,›3ÛƒU©JÝ™¥…Ã.Ý Ÿ"¿yóý(§¥GE³”ɵ?‡;Íe“2ÿ4‰‹jÓP‹IZ÷F¡·i“F÷*Ûi§%±¹:¯$Ù+‡!Í~ï ýA­>Ë=ý"ÛJý&ç‰fùÁgá3Ãï?—?•Ão©+Õ@§(áC³;÷:ã6ó©@ñ-¹TÑß0§'ßDÑ(ݵEó(¯*‘‡f¡xÑ%± Ý1Émùݧ3û/ÿ,·DÓ›n7‰Hãã8ëjû¹…xÛ(ý5ûC&ßÁwƒÕN­ÅMå[Ç'¹e‡¥[³?Ñ›…‡j·d‡3™Û{³WåWÓJÑ—P¡ ë£Ñ7/áfç÷™§ õ*ý_™`!ÍQç’õ-Û Ó©¿³’Ÿ mÏ"© “:å «~™%ýyÿuɱSÛ!ûaë=‰2á6éšå—9ï+‘wó í’“IË8׋#¯@óëßK‡!Y«4ÉÝlÉ(Ýo³ ÷¬©]Í¿Më0·"Õ+¯§S­}ÝÙ#×ã6×&k£oï&‡5…3™@·¿óBñ× -ù‹%ñ@—vË8ç -…©«³›×³ ‡^©;•{ó‘7Û#Ém‹ ±¡ŸÙ‚¹a…Ï»!#ó.“ ‰„5÷Õ Ý%û¯»s­a¥&÷Ç!k§C×÷ÉQ»/ã¹=¥“±Õ¨©‡¯:Í9Õx©hà ۩û‘YÇÙ“xÙϵP‡³³yï‰SÃw— ¯#½§Ï õ@¹{“ -‰¥ÿLÙ—a©@Ëù é^Í©O‘$Ÿ{û¯ ƒoÍÿ7÷Ÿvù‰)›d‹ …q;Û8ñ‹9Õq¿œÁ@ã -áIí=õ É=ù »çÍVQ+ñE9µ#ñ Û%Ó+‘#•&˃C!Õ“ ¯?³å7Ï Õ5«Dç'›$ƒãR¹ -‰<7·aÓ+Ù@¿0‰ §K½ã-­'-ƒ&ÿ7A­7½ -Û0•-Ó6Ÿ ó5ù?q‘½"ÿ‹ ñå ½(§E7Õƒ5#ÓG©·!í0Ç@%•Û¡"½%/ÑF«"ÿ­M'ãñ0í3Û#ñ ¥(ÏëJ=‘9½ ŸÅ!Ón¡‘r•#ÛÙoç —ÛhÍ+›¡qÓ!û -™=ç6ï±É@ã-©8‘@å±MŸ -§W•#‰µ,³bá'£KÍ¿ùgý­@«3¥é;›A³ “*Áã5µL·0¯ Ã2Ÿ?ù!»5¥Aù§&™Ñ:×+‘QëÍ ë"÷D×T©"Õ» ÇWù‘)Õ—8‘4•?Ù!Ë)ûCó ¹ó$émÑ ÛJù/Ï ëCÛ×ßDß8 ÿPéAÏ!í9í&/í$Å6íTˇ!‰(¿Ÿ‘…Å%Ï`ýÝ ¯Å ÷[¹(‰ à -•<…Q³ ßùí)Ñ­9— —é=Ù-“#¯»§.…"Ë í,—M»é ‰C%¥÷<½ »+ù"Õ ½*­!Ûï§8É0¹~±~­ åm¹—¡%…ù<›ÕL¿§9›ë<¥ -­L&ý©E¡"•C —*ƒß*Ý­5¡!÷ï8Ÿ Á)ÃÑ+³ ›&í ‘"ƒ0ÁAá“Eý9%‡ã:!Í@ó‰#ë!—@í‹%µ -ÿû+Õµ.ï3ë&ÑdíÅ5¿MíxÍ ½¯­g™ ‰!‰?ãã Ýc;™BÏE­!§™7÷£D•Ï¥3ƒ3Í+»Cm£¿ËÏý@Õ.‰ -Ý$ÉL]·ë"Á ³ƒPÍ ‹8YÙU©— B;Á:¡—6Q‡••§/‹#ÃeÓËÝ?õÙ ¿){‹ã(ý>­à ٠Só=Ýe¡£4Ý7ÛÝ@ù$§+³¥:Í(ÛA£Ã)»‰­8Y¹ -—8‘6•‹ãRû áõ>§¿D A¥D§ ­«daÝý›FÅ"M› ïAk •f±Ó6Ó5_õ#‘ ­kûA¥)¥1ÛJÝ!«·2J­“ £-ûP«óW…>“D»žËTñ¹I‘7Ÿ±¡lí » µ…§*…‰![÷±-“Ý-é8W§#Ý;—«õLóÿ—µ™)ýÍ‹A[ç5‘»5‘9cÕÏ'› -Õñå‡Ñ -ñYÅñ"Õ*½0¹@¯¿ AÝIË:ÉÓ4…¯"×¹£7õ £û=¹0ÝŸ¡S—‹µ—Á“ÙhëÍ/å2û>¹)ÉÅõ+Í?¥Ý&í¹ÿ¯‘+»¿éb±³)¹‰ ¥Ñ‘(¹.ù:™Ñé ¥3Û‹§›)_ñ-‘Õƒ‹aãÉ ÁùZ‘Ç«8—)÷ý­ÓÅ Ã&Õב Ïù©A×ɃßUÙÓ Ù(™µë*ÉGýÕßå½ ¡Ë)Ññ?ᓱý×)ßZ«ÇÇ,©:—ó‹¡3ß6ç]‰XMƒ7Óe­D×ÿ›…–‡1DÙݯÿvù ín“ç›óo—?§ÿn· ÇA?‰ïD‰eÙ9ÕsÕœ™GÏA¹8ómËA¡ß!ïAÝ1ë3á™)÷ ›3Ÿ.ÑMË …½)­×!“A‹@Õëû%™(é ›·3ß4UëÁ¥]µ8å2óá ׫³1»÷ÿK¯Û)ËûDËÙ&χÝ/<ÇÙF™'³ ­Ïµã¡XÇ߇«`÷é4“é£_ùl_ùYÍ“sýᇃ -—NW‡å ³ ñ•Zƒû+‰ƒ —]·5Ó†»«·ÅçÃÏZÇדåû¿Ë…ùãg•QåQ í'‹0‹û(¯Š¹ûvËN¹½¥ -£Ù½n•5‡/ï ÷±&ÃãóíY¯§ -ÿ%…#¥*å'×0õ#‘ë… ½ñÑ Ÿnß ù÷·±×.³ ¿9;Ë?§Åóß?»CçÙñ:ñ¿Õ¿0Ÿ+¹½ë«8Ù¯$«×@ý­„á—ÅEû…‹ß§IáÁÿ.é áH¥Íbý Ç1/Ý'åJ§(—‡JуíïÙK‡G•Ù÷Ã!µ'Û§?±Eà ÿ ï Á¥Gã³ ‡ÿTû±¥,“EéÇ;Ï·#÷«íXïű*‰óÙ#åKó -ÁwÅ9µ=ÃB•`·Çë•›ù9õI½#ÙÙ »D› Å3¡­WŸ£‘ÇpËBÙS«ó§H¯ ý•m±$çÑ"“&û;ýµ³!£¹©Í\ í!ÃË -¹³TßïT·F™!í µ'Ý#ë'õ» Ã&ý:åÉÍ6½ …aÿ‰Ÿ"•0á ù"=á‘W¿ÕEÏ-±Bé4± ë û9¡(Ë,Û%Å%à ʼn‘S© ÙÓ)íkó­"“?—1Ù(ÙÇC'á"·6Õ9Ã÷¹¥Ë+—£#Ã¥‡@¿%¯L¹”Ý(ûoi ¡d‘ £ù‹§1ë?7«ó e‹ ¹9Í(§‰=…™ ©‰K™ áK“©8ñÑO¿IÛ¯û%™©w± ó.§!ç×Nç ÅÃKÍS¡EÇdÝLÛé‰Ù ³kÅÛñ,ç3ñN­2£Re‹÷O‘{¿g—ÓNEñ³7ËÃgÛYÅ©7ŸÏ>ë™Ãã/ñ6Çù »Ýžá€­Ñs—÷‹7¿^å 4Ñ2ã0» ½›9‘ ¯aÉMµí"ŸgïUá“'¹y…§ ‡YÏó -ã ¥+ëy£ƒ ÏÝã/ñ½56«ù&‡"1‡7…{û «ù¨Û£:ßšµ -Á+ƒ Á~É•=ƒ#Û‹·Í‰ÑŸ íW« ÙMƒ ¡cù;ÿZÁ%± õ¦•Õ’Õ£7‘B‘ £"ë+÷€"“1ó6ÓÇ’çù;i•#½ ‹ ¥4¥Mñ±7ÿmëᘷ »˜± ¡lï é÷…u·4û©ûõÙvé5“Eñ8Ã5áL™˜× -‘Ã!Ï~‰'û<Á"ÝH¹7¯>‰í -Ÿ—%Õ{½2ùL—!ó‘³\áUµ>ùAÛ˜³ ñ~‡#߇ õ0å8»r£7ÓÓ’ù,å Ë8ÙL¹SùÕ"­|ÿj›#󟘡8Ë3¥jÙ3Å(§n½cÕLÝ!Å-ÑŸ}÷4¡Á0Ý8ï•Õï §a¿‘#…¯8‡5¥t¹4µ{Û›4×c¯…}5óÛ Ól½k£Ë‹ëí>ÇÓM‰'é ã'±@é[‘7Å -?ó•µA­hM·;Å"õI¡Põ?Ý™ÛOí ƒ%˯ó,,¥_›¥8ë ëS¹hK÷ ç8Õ »"ýpO7ÿí#»!õAÅUã$“[±Y‹ËdßiÁ¯¹“që--ƒ*¯"³½7› -™hµ!‡ a©pé$…A»Í6·7ÙJ]§Dá7õUíW÷#Ë“>©¡ ¯8ÑJc³$Ï·ÿm)Ù9›çç¡8ù›eû#Ý·9kí&÷ ¹$[ùl±]¯AéA…JÝCU—Y¯9Á Õa›!å¹ -­Û6ïAñiŸ›mÕ -eç[ñ· ã»{ǯ‰[õ*ŸmŸ å"—;¹q—Ÿ5ÿ/¥ïÅ#·"¥qÁDûÙ"o³ c[Õ‘=û“.ç »,5Á…å‘Å$ùcã3ÅûS©9­ é7åŸi‹8ýo¯SŸéSÕÿ¥ÏWå(û ÙgÑ"ç9© 9½Áe·e…×a»Á!Ó Ý…É§ ÷9_••§ ½‘µ—«™a£¥_µ7Å_ •#§"µû?± -ý‡ý íjÅ!‹O·5g«WJ‰ÇÍ åA]õ¿ó#Óç!¹OŸ(ñ­ «,¥ cï;©#ÝIÛ1_—ûU™ -M¿$n³© É1‰]á;ë#S¹ ÁÕ‡éåjí+•Ùuã2eÙ"›!¿¯ã(£û8O››v_‡ ï!µuQÇ?W×$ŸDõÛfÓW•KUë5©Ï½9•/— ™@Ë -Ý6kÑ&ÉÉ@ ]ó?Çv͈Ñ,ù§¹n‡)O…k¯ ³†Ù¢¹·]“‰Ñ‘s×õxá ¹fiá Ç ‡-ñ/Ý'“Ë á<9qÅ!ß!çi¥ QùÉ#Sí©É7±P§IçUÕ_ƒý£—0›`ƒ ɽßùË ÍÑ(ÉRaù á8ió¯‘<­‹P±SÙmƒ —1a‹ -ï8\Áž‰ ¹…ý •SûŸÝFÝ/«;5‰%áBJ• å3—c×Nå£ ñ ƒù6iÁ£nù'ÕÃÙF—ß#WÕG‡IÏ7û¿ßw£a×#Ïÿ« ß’á ýq¡½§2•7Ï6M«K#Y‹(­%Ý!±E¡ kÇÓß©·’ͱ— -…gû —#ó -É.•å•xï-{‡­µI‰ÇÍ$çe­ó5§ŸªMg­nW•ã _7½CïkÇe×£ω©"_WÁÛ¿0‰áÏå]Ÿ¢ÁÛ×7ŸÿIÅ·9¥oŸ8ã Ï ‘Å2Ý]ï7a‡£í¥"×pQƒÝ³8µ ×ß›-ÿŸK«L™’ï -ÇWå Ñ°¡Uã!+×XýS‡UÏ ]Å ã<å»Bm»‰8…[ÿÏÓ6Í -·Ë8ó _Ñ›,• mÝõ— o÷ Ÿ4ë…L‰‹×ëeÇ×óT‡DµWñG‘cÉñõ -ÍR¿[÷7û -ý‡Ç“µç9åOñƒM“VÕ G…Y‰‘yŸ -É$‰!Gßù2ßé.¯ -ß3ƒÃ§ _‘£6¥‹d£÷Í¿JÛW‹ÿ:½-ÃEAÅñ٠é Ç8¡"Ï w½m…Ycé^±!Å¡ç³$ñû»I٣ŠoËË¡"õS©2éû Ñ"kë¡’‡*{³ƒBOñ:ƒ­;ó!å³KÙɧ?×m±)£Dù…4¹Qá¯"©Õ -Må=û™S¥×"³Eõ¡9™k¡¯ õ8“ Ÿ;éŽÓÅ'Û`»5ó ]Ñg§?‘ù!û%kÛ'íbË© -¿­í­1¥i³‡ ÃV“.ÍK‰!™}÷§zß7‰NS©/«£ÿ•£˜ï‰ƒA‹$¯a“ ÿ —"“]“©7á-åi£Uõõ…¯1™UÍ«“Wk± µ7¡YÃn½”«½8¯ -Ññ …b³7ÿ‡WŸ;¹¹Ó÷!¯g•¿ñï -¡ åZñcƒ Ÿ ‘l…!IÛ -½&Åm_ÓQ—5ç7Ó£ oÕ Éd­ ÿqG“Z™õÅ7™ Û@³»6‰o‹aÃ"çzFÃ!‹ ý¡µ­“« á3é:_»óhÝ û:]—› •]û"ŸmíL×õŸ Uñ -å9‡§‰Ó‹_Ÿ U™#¯"…"ÃGûë ±‡ QË#·"o›#›’½<§Íƒ"¿¯Œƒ a»ƒpßY¥(ÿHÉ(Í6Ï;ƒ(‰_ùãEU¡8« ó@Ë2õ_‰ï6ë_‘3©"½Ë­*ÅÉmÏ•‘Áûh½+Á Q·AéOË+“\kßÇAã¹Å ùyýA“7ÿ›±$¹EÛé#¹Ç™<ÁÛ «ç Ù« ¹/±ïrý£³'¿™MÓÅ 1gçt·ß¯$±NÿŸ$¡­jÙ0ýùÃ,‡"éñ9× Ç÷“Åõ ëRõ©ó45‘É í“ÿýCÃ6·"¹­ +¡› M—ËóDé ÿ:•p4¯lŸïn‘Ã1ÿ/Ánýe«Ãm¿7½õ–•»OÉ™§‰²Ç¥(é|éÿ!™ýV»<­.Õ@ƒ ñtë áKË.—v`«SõÕë+§=³.‘s¿ñlá%¯<ÏQÅT³'û 㻽¹÷ù0÷S£(§µ•!‹ -ÍÝÕ<ƒó•O§¯ƒ -ÕX·3±,÷ïµ—)¿¥]³DÝ ‹ÙTé%ç8‹#ý»“¹1ý!‘«%—¿1å&•Ã‹ßq¡Á%£ -»QÉUïõ?“\åA»*ÃN‡•4ÿ¯ŸW¡0ŸÑmË!Å8«2©½bÿ>ñB¹©’¿ŒµCÛ ÉJÑ~Ù*Ïlñ‡Ç5¯S¥Ií6±¡oÍçMš±:LŸ„É:¡¹ ãGý©¹¨Ó¤ãlÅdïmé?çL½'©o³>Ÿ Óõ·4Ï%¹H›~Ñ9Ý -£ç)±Díñ'ïp3×g‹ÏŸ•ª³ÓT]×&ÝH³D™K…ʼndõW‹Jÿ«›‘s݇q“« DÍu£ÑR­σ­rŸs›­Ï„­IÕmÕ<¡³=£Ÿn« ß ƒ›Hó[û7ÕÓu“‰·£›±7ý¯Ùzù‹ë£¥hÿ>Ëjy§ï@¯cÏ9‹Ϫ/*õ@Ë8Ãíï"iÉÓ@ý Í­›NŸ?ų:ç7µ© -™•¡ýríñ ×Ý[×6¯ Ç$Ýmµ û!‘>8­ÅW›eɵóŸ>å8»ß9£BÓ ‘C—5‹5¹>…:‹Éq£"¿S©³#ë''¡@¿“s×9_±£"óu±%•"“4¿!Õå‹8é AŸjŸ ‰Y…¯Ç(Yù™"Å™‘¿,¹!ƒ[Ÿ•.·"ûÕ&µ(¥5£WÕóÿœçÇ“”Ù)zÁ2÷7K¬™k¥R÷󽃉 ]Ùc ƒ'©ƒÏ ËUã©!QÇ€ÍK»…P‘!áÅ¥I£B…ù$éeÏÍ…‘^‡ ¥'‘Ë› Ÿ»&µ#᱿e¯Ñ çZ -•'“íYË1•[ -ÿV£L“5ƒM—eáM¿šû áN¯7Í Ï!Æ« ù]¯ ÙO·!ÍY…±’É ù Ó!Ùù7·lÅ ×!•7Åí7ëZ7ŸñËe¡!¥ ™Cµ9±× ÿë!ß‹¡#ÿY¯ý]é:Õí·$ûy¡¿Œ÷)¡ñVÛ ã=ÿ é‰:ãC¡ -û¿ ϳ|É…|ÇNÉië"µñ}«[»"ï(¡ ½M©7Ÿ6§P—ÇýEï7‡£9£ÇˆÇ$µw¿7FÕá`å¹ ‡7½v9…·9ã…‘‰7‘Në8Ñ#Çl«3½NÙnó §’á™K—7—OÉ!ëañ ÷`å û,½ßaÿ §óx£v…9ë9§•™ -ù;Ã9Ù{•Z¿#³b¿8¥<ï -‘L½5m»!ë\Ñ ÷uÑ:µµ5« ï"Åg‹0ÿ ‘Sá ¯J7±W… Ç9ÿ —_ÿKÇVÍÃ7é"•?×ýS£&¹Ká ­‹/÷&ß«6ý•¥ï¯5÷Iç¡»Ëù@™§ Ó"ÓKƒ+Ñ”¥ˆïžÑn»¡/Ÿ ÷gï ën -³%¹#Áé•É‹!÷Kß+­ç$Q× Ù - ±/¿¿ áCá$³ -ëÓf·ó£!Á;½GÙå -—ïF“¥#³¡í@…Ña©—ËD¹$‰!‹ÉgÁ½$ÿG·‹±“7ÓNã Íjã!ï%ÃËó"¡· —׈½ÿ¥"ß" é;õ€ë«_Kû5ƒÝÓJ¡ õa¥;³ é ¯Ž»ëï’ù@» ¡+Ñ Í÷•7ƒ ¯_…MÓc» ™zé8»eïA9’ÛÏ!ëï™Å!§§G÷;Ù`Í"Û‹Ÿ›7ÿç)ÑxÏK½7Ÿ¿“¯$— -\©8éaï>ÕÑ…86·)ûz­z"2Íçÿ6ËÉPípÑ"+“#ýÑ9Ó§4çVÛ ËÝÑ9ïZ•,Ññ©$Ó ÅqÏ"…&zg¿8×w™7¡é‘¯¡»£¿ã^™‡ß]9‰dÙ£ -ÉtÅjYÁ ó½IÓ’g‹z«?Ï@¹!‰©Iÿûjù“(×|á²Á]Á&›ñŸ• Ë ›I¯ª½lùvÍ3«ã\·J©B£eÉë&õ ç3Ÿå&Ñ ÅK±Yóé ¯+™Å-ù a¿8ƒ1Eç³$•§…4ŸÉñ+‡ é_ý¯%¿:á™!Ë1—íQ£ ÿƒÿ -×`EÏïÝ¥j/Ãé&•¥WÏñC÷3ǧ$ƒ7›µQ-³…8©×í!õ<ß™÷@¹)—(£5‹Då"©H¿Q•ß».ÙG£Fû]¹í ãu‰ ëõ*¿N^Å!Ç)íà -½éaƒ-‰ç&³N—Cï/¡ùCË‹OÇ]ÿÛÁ#óV«åÿ -‰±ãõiÍ!¿±Å)‡ ‹h•­¿¹‰÷å|ÁN%¹¥‘£•Û>ëá5Õ ™ Ùdñ"ÍÏf—‡4¿ï#ɇU«4¹}Ñ`·—Çí ÿÙFÃ9ßká ëñ-ñi£Ÿ6ç&ÛYµ¥ËÏ õÏ<» ¯”Ï<áAŸ û…@£‡"ó,ë‰Ýï[·½F…²Ç³›¡œ¹¥ãão¡k¹áËó!¿ª­O«)Å%— -£ï™ Ã/£#ëÕE™4Ñ6ù+û©ýï7ßb£]ïµIí>É6ï­‹Çë ¥C×W‘™·%ÇFí°­f·9Û­—‡íªÑ-çBݪÉnýcù{¿ƒÉ3»V-ÿé'ßh‡ ¯ Û¢¯õJó*‘Y‡b¹ » “û]Ë›&YÍ ½&·*ùF‘=™ÉA£>oó#ûM¥$W©6™&Yß.‰4Ã#ÝGU¥ÁígýDQ‹Jƒ6c©çÙPùÅ"ÍëÿÏ4á“'ÍEË3…³Ñ1‹W‰ëg½@u³D·÷µ _½S›+§=ß4ó‘K¯3k±3õ)¡OóuׯS™>½Rõ7»^»H×&ïDÁk¯û3gµKÇ+íSí1ÑI§#¯GñEå1›¥ßzÇ-;› Óu­0‰Ámc¥Ùc0uÕ#Oï µ]ùÑ)÷$·C‘ Ï‹ñï—¿3ó”¹`ë©»t™å—Ï5„ݲÑËÝ=µ%Ëi‹/«5±.©sáãŸÓ£HßwíÙ “Á¹>ÏZý@/›ïa;9£§…›ÇÛDÛá·-m÷%ƒñdÑ-·ž»“£(· é“J5¥9‹¹uóÃ/ŸÛ4™3Áw¹#ûí"#³'›Gƒ2é3½ -¹RÇß2…×É©tÛñl9Å9½¥_Ý9/<—í2û1§ 7“pã)­œ;ÃÕ•#­¥ Ãc£3Ñ Ù˵&?à ¯M¹••“‹ûi陇$¥ ñ Ç™6…)Ÿˆ¹Ÿ,í2Ó¯9Oí=ω §_1Ý ­¿9§BÇ[ûNéõR‰w­‰+¥7—°•¨é˜·û–ï=É5ãÅFÅ.± -?ã]Ï2µV -“.ãPÙ"± ³O£û¥+ƒ$™£ -¯>©Ç#‹û^Ý«0³"?Ç« “(õ½O…™¹ížÕoß6­‡ ƒ½)í›á3ïÁ.ý-4 ‡ñ— -@¡I©íF»?ñG§Íá&ÑC™#õ%ÁŸ×JË7ÍÅ‹7Ã*éëg³‘‰¯û‡HÛ(ÿ¯@‹P­ ‡&å>½‘J¡»NË"Ó"ç•›2¯7¡½Ë%Ù± µ¯L›9ó -íMûÝL÷Í]§)¥…ëS»å ±#›Ó­… ùƒá …‡$Ï›g³‘Ý5£Í á9÷õ:¹ =Ù&û:ß»å8û×ïB‹ ›&§,ó £ “ÃF™$­‡Õk‘Pí$É+« í(ã*ß ¯¹ß&¥W¥fŸHQ…[á cÓ û ݹ…ß0ÓSÕ1ÙC)ý «k«­ É -ý9{×hÁ -¥EñUù -ÿ5YÇù9¡ _•,¹!ƒÃ9g¿máD¹‡(÷å8ù+Ùß$§í÷—*ÉEaÿó—"á -µzÉ“ýžµšÏ¹ñ!ÿ'cý…•Zƒÿ#‹7…ˆçç¥IÛã1‘#ëMµd‡Q‘Í¿ ÿ¿Ç£…o‰ -écû"¹zï8ÙQ‰ ñ5×édãDý!»Aí¯)ñD"Ÿ-å"ÅJË ©9ó ×@Ÿ$­$ó -ÿ8É%­"Ÿ¡(ÝPÓ ­:·9‡4Ç ƒ Õ<±@ñ$õ‰99í#éõÏ/¯Ï ×D»+ÓÇ)µ#ÉO×'ñƒ ïNã÷<© ûAå%¹"(û…¥×L‡"íÇ4?ñ3í×lûÇ -ý$ã¥6C»GÇ*Ù7Ó'½C¡ Ã:õ ß)JÇáól¥ µå7ÛõFá« -ÛPÕ>…*¹‘ ý6Ùë±\›ÿAÛÁ›1¯ -é4‰?4Ó!ù ¹?ÕE³³7ñ8· Ó(ï©?á “‹r¯± “©)ƒ9åë×#å­Ñ&õ!¯RÑ­¹8Ë%÷#ã(éå8·@µ © ï -éOïÝ4£>“r¹L©6—q§£Ÿ©$‰FÝ—rµ"‰E‡.Á çhÝÝ•"ßnë‘Yý ã:— ŸJÃý!ÑPµ -Ý›0Ñ#¥) íSÕG»ëG‡±#ã—Õ/«6Ù9û±+‹Ûl§vÇnç õ …7Í>÷ûLé*‘"¿]× -Û/Ûn÷h»÷ ‡-ÉF+«!ÁWÙ ¯Ñù‡ëD‡-åVóI¡+ƒ"¿dý …6©B³Ƀ -å9¡ ­‹I‡’韓ýÑ¿­• ë;à -±6³µ9«2ÍUû"Ñ#‡£‘ñbùáGù)‘®§d•£å¥í©±­<ûP·׋Û -Í"ÇI‘*³3·ˆ•Áiƒ˜Ùf“‡S™¢åµ?ñr™•6 ‘'óRµuÃZïKßE­:à Ïg‡,™w¥·£Ù7ýK›-ó¬á*™ïl'…ý ÷%±Sùá&ÅÑu›÷‘%‹EÓGñS¥ ï~ßV‹,ÃÙJ©K‘tÁy›ÙÉ0ƒ³2µDó‘Ë9‹‰©c¡ãW“—P1û Ù§ÛA¹9Åhå'ÏÇ 5µ«—õ ­3Ï3•5ƒ ƒÁ%ñ ñíÛ ¹*^ñ1Ûœ©mÁ…™Ýõ1sÙß&íÅñ3ýùçÑ7§EËEÙ ñ½?…BÁ¥ Á'ƒ.ã Û3××Ç|ë ¹-ó“Uñ#Ÿ!éN½íÁT 5×!ÓZý}Å ©"Å?÷OÑÃsõ³÷¿6Q£IÝ]ÉÑ7¥ÃYé¹ eá^ÉÉDÁÉñ9-½ªÃ9Û~»·‹9˯1±¡¯ÕA«"ï"½ˆÃP»<‘Õ‚!­6)‰±-á÷{‘5Û¯¨Óµ‰!ÿw#ëv•\¹eÿÍE¯xí…‘¿Q¯ Å!Å7‰7·SÇ>« ó<Ó>» ·‹#­D‰‡LÙO­ Û;6Û:Ÿ”™å)õ ½_‰ ·RË¥;‹kóë •<ÕBŸß8µÇL¡]嫱Q³>ÏÑçAÿ©5éA‹;ã ½DµBõ©Wç«ÕAÕ3ÑF× ½*¿A០ÑDÏ8±!¡I÷!ó8³9ƒ*·:×3ñûGýJùO¯•#Íñ ¿P­S‰“3—‡ »,éP« -ÿr¥õ=¡ù¡:ç©/³$Ó"µ ç&— í6¹'©RÛeù#ák õ†½DË µÍe—¯ …rß&çzƒ›Ÿxåÿ¨ÅŸ µ8ïŽÁÁßSÙœ‡˜Å<õe‡%µRË Í9¥mù )É"‰›4é ½ó?©&ÛA‡4£…kõhã)Ù© å$ŸË4‡Vµ5»¡\éßç*Ã\‹8‹“Ã"³ÕgíŽõ9Ó>÷-Aù ï…›ߊË Ëóvëf&Ô©Ó=µñ) Ý<¹ér½Ç&ƒ·!á‹ápý -é· ™#÷]Ù ±7“NÛ6¹É -µ aŸ¿ ‰ÛOÁ—ߣ&ù·!å­*ÇL‰4Ï™ §8•¹Aó ‡2ß -³/Á<óÍ£&ÁWãÃí á[Çñ §0ï ±¯u£ÿ™ÍZý õ‘.£íC×7±»Ï­“©›=ƒ1ᬡ¿2™É -Ù+å¥'átŸ É_›#‡y‰3áÓ1é1ñ.í³:™é ËŸ¯[ãùI-ã*¿!ëŒóF÷(à -ý×É‘D"ÕãÍ6³*×@ç8Ñ@ç(é-ÿ«g3³,™6çƒ/·#‡.Ë­MÅ›,—Ûu‘"ƒS·=ÇN¿ƒ)Ï×z¥õJå*§"ýc½%™ñ‘&¡0çãÑ ±–©­ý+Û'Ï¢åQùÑ*¥*¥MÅñZ¡Ó.ñ¡<áÑAç ™× ¥ ±ßtYÿ/×ç1Õfóý ®'ù™JÙ éѧ„Ñë -·,… ¹Ÿ9­)›/± -Ñ4Õ•ïÓ6«6ó]ï Ÿí[ÿ0ûsé'陽mÇ å -³±=Û -ÁbóE— Ñ@Ñv¹B¥6Ý/‡ß’ý:¥#ï^Õ7é™ ­e§Pz»×¹;›Õ6ÿ?s!³é—é™võz횇— Ý8 ín­Ñ8ý!íï@õ(Í£Œ¡…É]Ï #ó'ÕE$µ‹#Ï •D‘¿©ç*±&ׇ&£!“€±$™$³Û"Í5‹Ié0¡ƒX‘eñý(×F«#Çõ3· Ý;ëÇ>.÷6³ ýÍ7å0‡9ùµÓKÁÕ÷;õ÷hñ£!‘£3Ÿ» Ó -ÏL¯ Ïï"ß -ÕAÕ2=ëßï%½+ÍËç‘—Wà ßß6•'HÕù%¥ñ3¥‘0‰&ï« É×4•5‹é½$ý%ë#«£…3ÍÓ÷׫[™ãï:­Z@³~Ù/Óí)³ÿ)ùPǃ&Ïõ·³•-µ;ÑÍÙ¯!³ ¯RÝ&á=Ÿõ…ù• õ1½DÍ ï •µ7õ9ß=³Ã‡‹)Í0ÿ »ó­&½3¹§(Õ͹ “Ç›>ÿùë'›1‰ Ó!‰é#‹í å*,ùJ™™ã“$“!©'é%¡0çññ ù÷Ç&É(Õñ³&‰Ÿ Ÿ>© Ý!ÉÙÝ(—ë ³ƒ+ÿBÑ!×8Ýù Á -Ëï<ƒÉ -Ÿ4«ã˳ …tñ½¡¯ Ï{»h› ?‰*Vßç@á£&‹«FÕ²ùe—5“ …%ß~ \ No newline at end of file diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.nrm b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.nrm deleted file mode 100644 index dc21226..0000000 --- a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.nrm +++ /dev/null @@ -1 +0,0 @@ -NRMÿ|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||vvwv|vwvwvvw||v|wvwv|y||||wvvvwvwy||v|wwvww|vww|v|w|||wvwvyw|vw|vv|v|y|y|||vvvvvvwvvw||w||v|vvv|vwv||wwwvvwvvv|v|wwwvy|w||vwwvvvvv|wv||vwvyvvv|w|wvwwwvvwvvvvvw||||||vw||w|w|vy|vw|vwvwvvv|||v||wvw|v|vwvvvvvw||vv|w|v|vww||||wvvyww|||||vwww|y||w|wxwv||v|wvw|v|w||ww|w|ww|||vxvw||v|vvv|y|vvwyvvv|wvv|y|vvyv|wvwwwvv|wwv|vw||vvw|||vv|wvv|vywvw|v|v|ww|wvvwv||vvwvvvvy||wwwwwwv|w|w|v|wvwyvvw|||wvw|vvvwvv|wvwv|vwv||vv||yvw||wvvwwv|vvw|wv||ww|vvww|wvv|y|v|v|ww|vv|vwwwvwv||w|wwww|wwyvvwww|w|vvwwvwv|v|vvw|||w|v|wv||vvvv|v|v|wv|vv|ww|w||v||w|w|vv|wwvvwvwwvvvwwvv|vv|vv||w|w||v||wvwvwwvwv|wwv||w||wvvwwvwwwwv|w||vv|v||wwv|ww|||wvvww||w||wvwwvvvvvvv|||wyww|vvywvwvwvw||||vwvwvw||w||ww|wwwvww|vvv|wvvvww||wvvwv|v|w|w||w|vv|||v|vvw|v|v|vw|vvv|vwvwvv||w||vvv|vvy|v||||ww|vvwv|vv|vwvw|w||vvwwvv||wvv|v||v|yvvvv|wvwvwwwvv|vvvvvwwvv|wvwvvw||vwv|ww||w||yvyv||vwvvwwwyw|v|wvv|vvwv|v|vwv|wwvyvv|vv|wwvwvw||vvwv|wvvv|vv|w|vywyv|vywvw|wv||wv|wwvvwwy|vwvv|v||||v||w||vvw|v|v|w|wvyw|vwvv|wvwvwvvwvvv|vw|||w|vvv|||v|wvwwwvw|vvvv|v|vvvvywwvww|||vw|vyvw|vv|v|||vv|w|vvwvyvv|vvwww|vv|vvv|vww|vvwvvwvvwywvv|vwwwv|vv|wv|v||vwv|vw|wvvv||wwwvwv|||vww|vvww|vw|vwvwwww|wvyv|v|wv|||v|wwywwv|||wvwvv||||wvvwwvv|vwvwvwv||vvwwvwwwvyv||||vw|ww|wyvwvvwvvvvvvv|wwvwvwvwwvww|v|wv||v|v|vvvvwvwv|||wwyvvvwvvvvwv|w|wvyv|wvw|||w|w|w|vvwv|vwwwvwwvwvw|vww|vwvvw|vvv|vvvvwwv|ww|w|vww|||wvvv|vvw|v|v||vvwvwvvvvv|vwvvvvvwvyw|wwvy||wv|w|w|v|vwvwvvvwvwvv|wwwy|y|vw|vv|w||wwv|v|vv|vwyw|wvy|wv|||wwvvyvw|y|wv|w|w|wvvvywvw||vvvv|vwv|vw|wv|ww|||v|wvwvwwvw|vwwww|w|w|vwwvw|w|vw|vww||vwv|||vwwwvv|wvvvvv||v|vwvywv|v|vvvwvvwvv||v|vvw|ywv|www|vvyw|vv|v|vww||w|wvwv||wvvv|w|wwv|vwww|wwvvvvwv|v|v|ywvvw|vv|vv|vw|vwwvwv|vwww|v|yv|v|y|vvv|vvwvv|vw|vwwvwv||wvwwyw|vvvy|vv||ww|w|wvwww||ywvyy||wwyvvww||vv|vww||vvvwvvvwwww|ywwvvwwwwvvwvv||||vvvwvwv|yvv|v|v|vww|w||vvvv|vvwvvvvw|wvvv||ww|w|w|wv|vvvvywwvv|vv||vv||vwvvvwv|v|wv|vwv||vvwv|vvyv|vw||wvw|wvw||||||wwwvvvvvvwvv|vv||wvwvwwy||wywww|vvw|vvvvvvww|vwvvvwv|ww|vwwvv|ywwvv|w|www||ww|vwwwv|wvvvvv||vywv|v|wvvvwvvv|vwvwv|ww|w|wvwvwvvwvwwvw|v||w|v|v|vwv|wvvwwwvv|||vwvvvwwwvy|v||w|w|vv|wyww|vwvvv||||vv|vw|vw|w|vw|v|vvw|ww|vw|vvv|vw||w||w|wv|wv|vvvvvwvw|ww||vwvvw||vvy|vvwwyvv|vvvwwv|vwwvwvwv|vvv|vvv||vvvw|vww|vv||vvwvvvwvv||vvwvw|wwv|vw|ww|wv|wwvvvwv|||wvvw|v|yv|vvyvw|wv|wwwwyyv||vwvyvyvy||vvvvvwvv|vwv|vw|wvww|vv|wvv||wvv|wvvww|v|wwvv|wvvww||v|||||w||w|wwv|wvww|wvv|vv|w|vvwwvv|vv|vwwww|vvvw|y|||y|vw|w|vw|vv|v||vw|y|wvw|v|||vwvyvwww|vvv|wvw||v|wwv|vv|||vvv|vwvv||v|v|v|v|vwvw|vwwvvwv||vw|||vv|vwwvvvwyv|vvvwyvvwv|v||vwvv|wwvv|wwwwvwv||wvvvv|||vwwvw|||wvvv||w|vwv|vvv|v|vwvwvwwywvw|wvwv|||wvw|vvwwww|vvvw|v|wwwvw|v|vv|wvvwvvwvvvvvyvw|wvxv|w||w|vvwvvww|vv|vwvww|v|y|y|||ww|||vwwywwv|||yvww|vvv|w||vv||v|vwwwv|w|vvv|||w||w|w||vwvvwyw||vv|v||w||||ww|||||v|vwwwvww|v|v||vww||v|vvvvw|w|vvv|wv|vww|||w|wvv|vww|wv||vvvv|wvvw|||||v||vwww||vw|v||xv|ywv||vwww|ww|w|wvv||wvvvvvwvw|wwv|wwwvw|w||vwvwvv|wv|v|wwv||w|||wwwvwvwvyww||vwv|||yw|vv|vwvvyvv|v||vwwvv|vwwv|vyvvvw||yvw|wvwvy|vvvvww|wywwvwvvv|vwvvwvwvw|wvwv|wwwvwwvv|||vwwvw|w|w|||vvv|wvwv|vwvvyvv|ww|vwwvywwvwv|w|vvwvww|wv|v|wvvvvv|w|vvvvwvw|w|vyw|||v|wvwywvv|wvvvvwvw|w|vvwwvyw|w|wv||w|vvwww||||vww|vvvww|w|vwvvwvv|vvwvwvvwwv||wvvxw|wvvw|vwvwv|vww|y|v||vv|wvwv|vw|wvw|wvw|vwvy|vwwv|w|w|w|vv|vvvvwvv|wwv||v|w||ww|wvw|v|wv|vv|v|v|||wv|vv|vv|vw|vw|||w|ww|w|v|vvwwvww|||vv|v||vvw||wwww|v|v|wvwvwv|||w|v|v|ww|w|wvv|wvvvvvwvw|vwvww|||w|vww||wwwvwv|vwvwv||w||vw|vvwv||vw|v|v|vwvyv|w|wv|vwwv|v||wv|vyv||v|||wv|vwvw|vvv|vw|w|||w|yww||||wv||y||v|vvwv|wv|vv||||wv|vv|wwwww|||vvwvw|wvv|vwvwwwy||wwwvwvv|w||||vv|||wwwyww|vw|w|ww|vvvv|w|vw|wvwvwvw||v||vwvvww|wv|||vvwv|vv||vvvvxvww||wvvv|vwvw|wvvv||||v|ywvvwww|www|w|v||wv||wv||w|vvvvvwvvvwvv|wvvvvv|w|wvvvwwwvv|wv|wvv|v|v|vwwv|||wv|y|ywvw|v||vvv|w|vw|wv|wv|wwvvwvvw|wvw||v|||vw||wwvwv|y|w|vwv|w|v|vvwvvvww|ywvv|vw||vww|vvwv|wvvwvw|vvwv||vwwv|v|vvww|ww||||vyvvwvvvy|v|vw|v|v||||wwvvwwwv|wwwwvvv|wvywvwwwwvv|v|www|v||v|vv||||vv|wvy|wv|vw|||wwwwwv|v|yvw|ww|wvwvwvw|vvvvvvwwwwwvv|wwwvwwvwvvwvv|vwvvwyv|wwyvvwv|||w|wv|w|ww||vvyw|w|w||w|wvvw|wwwwwv||wyw|y|vvww|wyy|||vwwwvyw||ywww|wvvvwvw||wwwyw|vwwww||vwwvvvwww|wwww|wwwv|v|wwyv|vwvv|vwvyv||wvy||vvwv|wwwv||wvvvwv|v|wvw|w|ww|vvv|wvww||wwvy|v|vw|vv|wvv|vvv||wwwwvvv|w|wwwww||w|vvv|wvvw|vv||w|y|wv|||wvv|vw|vvvvv||yw|w|vvwyvyw|vvyv|wv|||||wv|w|vvwvv|w|v|||vvv|w||vv|vwyw|v|wvvwwvww|vvyvv|w|vvwwwwwwwwww|vv|vwv|vwvwv|ww|||vw|wwvvvw|yw|wv|wvvvwvwwvvww|v||wvvywvwvvvww|w||vv|vv|vwvwvvwwv|v|||wwvvvvw||vyvww|v||v|vw|wv|vvvvwv||yvwv|yvwvwv|||v|ww|vvw|w|vvwvwwv|vw|wv|||vwv|vvwvvvwv|vvvvwvvw|vvv|wvvyvv|wvvv|||wwwwvwwwv|wvv|wwvwwvvvyvvww|ww|v||vv|vwwv||vvwvvv|wvv||w|||wwvvv|w|vvv|vv|wvv||||wvwyv|v|vwwwyvy|wv|vy|v|vvwvvvw|wvvvwvw|yww|ww|vvw|wv|v|wwwwvwwv||wvwvwwww|vwwv|||yvv|vyv||vvvw|v|ywvvwv|v|v|v||||v|w|vww|wwwvyw|www||vvvvvwvwvwvvwvvvwvvwvvww|www|vv|vvv||||vww|v|wvvv|wv|vwv|vv||vv|wwvv|vww|vwwv|vvv||wv|v|vvwvwvww|v|wvwvv|vvwv|yvw||wwwv|w|w||vv||y||w|vw|||vwwwwvv|v||vy|vwwy|wv||vw|wwvyv|||vywy|vvvvvww|wvw|v|v||||vvvwwv|||wvw|||yvv|vyw|wwy||wwv||v|wwv|w|vv|ywwvwwy||yvwvwvwvvvvvwvvvvywv|vw|vvw|vwv||vwv|w||v|vv|vvvwywvvwwwv|wwww|vv||vvwvv|wvw||v|w|v||v|||||vwvvwvywvvvwv||vvw|vwvvwww|wwvwvwvvv|vvvww||w|wvww|vvv|wvwwvv|wywvv|ww|vv|vvv||yww|yvv||v||v|vvvv|vw|||w|vv|wwwv|vvwvw|wwwwwvvwyvwww|||vvv|vywww|vvwwvwwvvvvw|||vwyv|vv|vywv|w|vvww||wwvwwv|||vwwyw|v|v|v|wwv|v|wv|ww|vyw|w|w|wyv|vwv||wv|wy|vw||vvv|wvvw||vw|vvvwvywvvvwvvywvvvv|vvvvwww|yv|v|www|vw||v|||v|vywvvwwwwvwywvv|vwy|vwyw||vvw|wwwwv|w|wv|w|v|vv|wv|vv|www|vwvw|||vyv|ww|wvw||wvw|wvvy|vww|v||vv||||wwv|vwwy|yvvwww|wwvw|vwwvvvvvwyvvvwvwvy|wwvww|v|ww|www|v|w|v|vwvvv|vwv||v||wv||w|wyvvvvw||wvvwwww|yv|||wwvv|||y|wwvv|vvwvw|v|vvwv||vwvvvvvvv||vvvvvw|yywvvwv|yv|w|ww|vvv|vww|vvvv|wwv|y|wwvwv|wwwwyww||vwww|wwwww|vvw|vvvvwxwwww|w|vvy|v||v|||wvy|vvw|wwvwwv|vvwwvwwww||vvvw|w|w|vvwwwyvv||vwvw|ww|vwywv|wwvvv|wv|ww|ww|wvy|w|vyvwwvvvwvv|vv||v|vvwv|w|v||vvw||vvvv|vvv|vvwvvww|wyv||||wyvvww|vv|||ww|wvww||v|vvvvv|vwwvvvywvv|vvvv|wwv|vv|wvyw|wv|w|v||vwvvvwvw|vww|www|v|ywv|w|vw||wwwvvvvvvw||ww|vvwvv|vvvywvwvv|vwwwvyvwvvvv|wwvvvv|wwvwwwwwwwv|w||v|wvvvvw||||||wv|w|wvwwvvwwvv||w|vwwvv||v||vvv|vvvvwvwvwww|vvw|wv|w|vw||vwv|v||||w||wv|vvvvw|w|v|y|vvwww||wyww|wvvwvwwyvv||w|v||wvvv|v|w|vw|vvwwvv|w|v|v|vv||vwwwww||wwvvww|vvv|w|vwvvwvvv|v||vwvvwwvwvvww|wwv|vvvvwwvw|ww|wwwvvvvvvv|v||v|vv|v|vwvvvvywyv|vwwvwvv|vw|vww|vv|vvv|||ww|www|vwv|y|v|vwwvvvvwvww||vvvwvv|wvv|wvv|vy|vvw|wvw|v|wvwvwwywvvvwv|wwwvw|wvw|wv|v|vyvww||vv|vw||w|yv||vv|wvyyvv|wwv|vy|vw|vwvvvvwvvwwvvvwvww|vww||wwv|vwvvwwvv|wwy||vwwww|yvvvyvwwvww|||vv||vwvwwy|vvvv||vv|vvwvv||vvvvy|vv||vwvw|wwwvw|w|v|v|wwwvvv|wvwv|w|vv|vw|||vvwwvvwvv|wvwvvww|vw||wvvwvvyyvvvv|yv||v|vvwv|wv|vwwvvwwwvv|wwvvv|vv|v|vyvvvwywwvvvvvwwvvv|w|||vvv|vww|vvvyvw|w|vvvvvwvvw|wvwwwwvvwvvwvw|vvvw||yv|vwv||wvwwwwv|vwwvw|vywwwvv|wwv|vv||vwv|v|w|wwwyvw|wv|w|vvwvvw|vv|wwwvvw|vwwvv||v|v|vvwvwvvvvv|wvv|ywv||v|vwwwwyvv|vv||wv||||w||v|||vvv|w||yvv|||w|v|vv|y||vvvy|v|||vyw|v||yvvw|v|||www|wvvwwvvv|vwvw|w||w|v|w|v|w|vvwv|v|vvvwv|vwvvw|wv|wv|w|v||vw||w|v|wv|vw|||wvy|vww|v|vvww|w||||vvwv|wwvvwv|wyv|yv|y|wywvyvvwwyvwww||w|w|v|wwvy||ww|w|vvvvw|w|||vwwvvvvvwvv|www|||vww|||v|wvwwwwwv|ww||wvvwwv|wwvvwv|v|vv|vv|w|||vv||v||w|wwv|vvw|vv|v|vv|vwvv|wyww|v|vw|vvvvwvw||vw|vv|vv|vywvvv|ww|vw|wvywvwvwww|wwvwvvwv|vwvwvwwv|vvvw|vvwv|v||wyw|ww|yw||wvvwwv||v|v|||vv|vv|ywv|vvvvwvvww|wvv||v|v|v|wvwvvwvw|vwwwv||v|vvvv|vvw|||v|wvvvw|wvww|v|w|ww|vxvwv|wyvwwvvvw|wwyvv||wvvvvwwvw|wvw|v|v||vv||wvvvvvwv|wvvv|vww|||vv|vvw|vvvww|vvwvv|||yv|wywvwvwvwvwwvwwv||vwwwvw|||v|ww|yv|vwwwwvvw|vvy|wwwvvw||w|vy|ww||ww|vw|wwwyvv|vvwwv||vww|vvwyvwwvvw|wvwwwvwvw|wwwyv|vvvw|wwvwvw|vvvww|w|||v|||vwvwy||w||vwyww|vv|w|v|vwwyvw|vvvvwwyv||w|vvv|w|wvvwwvv|v|v|vvvvwwv|v||vvvvy|wv|||ww||wwvvwvw|yvvvvyw|ww|v|||wvwvvv||wvwvwvw||v|yvwwvwvy|wwvw|v|wvwwvww|v|yw|wv|vv|||w||wv|ww||vvvvvvwvw|w||v||v|w|wvvwv|vvv|||v|wwvvvw|www|v||vvvwwwvvw|vv|yvvwvw|wwwvwwvwwwvvv||vv|vw|||vwvwwvvwwvwvwy||vw|wvyv|wvy|v|wwwvvvvwyvww|||vw|wvv|v||w|vvwwvv|wv||v||vwv|w|w||vvwvw|wvvvv|vwwvwv|vv||wvvvwvwvwvvw||wvwvwyvww|||wv|wwvwwvw|v|vwvwv|wv|wv|w||v|wv||v|v|vv|vv|ywvv|vvvww|v|wvvvvvvvw|v|||vv|ww||vww|vw|vvwvwvvvvww|w|wvvvvvw|wwwv|yw|vw|||v|wwv|vvww||vwvwwvw||vvvv||||||vww|wvvvw|y|vwvvvvv|vvw||vwwvv||wvw|wwv|w|wywvw|v|||vvvwvvwvww|vwvwww|wwvwvv|wvwvw|v||wvwwwvvvvvvvvyv|wvywvwvvwvvvvv|v|w|wwww|wwwvvwwwvv|w|||wvvw|vvv|v|vv|yvvvwyvvvwvvwwv|wvv|vvvvywvv|||vyvwvv|vvw|vv|w||vvvw||v|vvy|ww|v||vww|vv|||ywvvv|w|vv|v|wvvvv||wvvvvwvw|wwvvwv||wvwvwwyv|vvw|w||wvvy|vyvvvvww|||wvvv|vvvw|vv|wvww||yvvvvw|wvvw|wyvv|w|wwwwvwvwvwwv|vv|vwvvwvvwwvy||vvwvw|vvw|vwyvwvvv|w|y|vw|vy|wwvyvywwv|vww|v|w|wv|wv|w|vv|wyvvv|vwwv|v|yvvvv|vwvw|v|vv|||w|vv|wvwvv|wwvv||||vvwy|v|vwvv|w|vvvwvw||vvw||w|wvvww||wv|vw|wwwwvvxwwvwv|y|vw|vvvwwv|y|wwvyvw|vwvwwvw|y||wy|ww|wvwvv||v|vv|wwvvwyvwvv||vvvwv|vvvvvw||ww|wvvy||||v|||vv|vv|wvvvvvw|wvwvwvww|w|vw|vvvv|v|vvw|v||||||v|vv|w|vv|ywvw||vvyvwv|vywyw|wvvw||wwww|wvw|wvvwv|ww|vv|vv||vw|ww|vw|vw|vvw|vvvv|w|wvwy|vwvvvvwvwvwwvvwv||v|vvvv|vvwwvwww|wv||wvv||vwvvvwvvwwvvwvv||v|vvvwvyvw|wvvvyvvvv|vwv|wv|vvwvv|wwv|v|yvwwvvwvvwv|||w|y||||w|ww|vv|vvvwvvvwv|wv|vv|v|v||wv|w|vvwvv|wvvw|||ww|vvwww|vvv|vwv|wywv|w|wwy|vvw|vvww|wvwvvvw|w|wwywvvvvvvwvw|v|vwvvwyw|wv|v|w|wvw|v|vwvvvvwyvw||wwv|||w|wwvwv|vywvvvv|v|vvww|ww|w|v|vww|wv|wvwvv|wv|vv|||vw|v|ww|v||w|vwv|vv|w||vvywwvv|wv|yv|y||vvv||v|wyv|vyvywwyv|v|wvvywv||vwv|||v|vvvvv||vww|vvvvvv|wv||w|v||||www|vv|v|wwwvwwywv|wwwww|||wwvvw|wwvvyww||wwvwww|vv||wv|||vvv|wv|||w|vwv|yw|v||wv|wwvvvwvyvvvvywvvvwvv|v|yv|v|vyvwv|w|v|v||vvwv|w|wwvvwwwvv|y|wv|vwwvww|v|vv|vv|www||vwvv|v||v|vvw|||v|||||wv|wvv|v||w||vvw|wvw|vvvywvvwy|wvwwvv|vwv|y|vv|vwvvwvyywvv|v||vy|v|wwvvvy||vvvwvwvwv|v|vvwvv|vvv|vwvvvvvvvwwwwwvw|vvvvvww|||||vv|vvwwwvwvvv|wv|v|vwv|vv|v||wv|vvww|||vww|vvwv|v|wvvvw|vwvv|w|yv||vwvvw|vvvvvww|w|v|wwvvwv|vv|vw|wv|yv||wvw|vvvv|v|wv|wyywvwwvvwvvwy||v|||wwwwwwvv|wvww|||wv||v|v|v||w||v|w|v|wvww|w|vvwwvvvvwwvw|vwv||wwwww|v|||wvwvvv|||vvw|v|vv|wvvvwwvvvvvv|vwvyvw|wvvy|w||wwwv|yv|v|vvyvvwvv|vwvwy|wv|y||w|w|v|||x|wwvw|wvvvwvvyvvvwwv|wwvwwvv|w|wvwvvwwwwvvv|wv|vww|vwv|wwvw||w||vv|wvv|w|vvwwvwwvvw|wwwv|v||vvw|wwwvvv|vv|vwv|vwwwv|ww|wvvwvw|v|ww|||y||v|wywvw|vv|www|vwwwvvvvv|vwv|w||vvwvwwwvww|vv||vv|vwyww||vvw||vvwvwvww||wvvvv||wvw||wvw|vvwvvvvwv|||v|ww|wvw|vvy||www|w||vw|w||wvw|www|wwvwww||vvw|wwww|wwwvwv|v|vv|vywvvwy|vvvwvwvv||wvw|v|w|vv||wwwv|vw|vvyw|vv||v|vwvvvv|||wwvwv||wvwv|w|vwvw|||vv|v|vv||vwv|w|v|w|w|v||v|vw|wvwwv||ww|wvvvv|vv|v|vw|v|v||||yvvw||w||vwvvwv||w|wwvvvwwv|vwy||w|v|vwwwvvv|wv|vvww|vyvwy|vv||w|v||||w|ww|vv|v|wwvvv|wvwvv|wvvwwvywwvvvv|wwvw|v||vvyv|||vw|ww|wwwwv||vvwwvv|||wwvw|v|v||w||vv|w|vvyv|||yvvvw||v|w|wvvv||wxwvwwv||vww|vww|v|vwvv||v||wvw|w||vvwwvvvwvvvvvv|vv|w|wv|w||wvwyv|vvwwv|vv|v||wvvwwvvvww|vv|vv|||wv||v|wvv|w|vw|wwvwwvwwwvwv||wvvwvv|vw|vwvv|ww|v||vvx||v|wvv||wwywvwww|w|vw|v|vw||w|v|wv||ww|vvwvv|vww||w|vvww||vvvvv|vww||vvvvvvvw|wy|wv|wwvww||||v||w||v|vwwvyw|v||||vwvw|w|vwv||y|vwvvvv||v|wwvv|v|yvv|w|wyw|vv|vv|||v|||vwv|vv|wvvvww|vw|wwvwvwv|||wvwv|vvvwvw|vwwwwwvv|vvv|ww|v|vwy|vvwvv|||v|yvww||vvx||v|ww||vvwv||wv||vw|w|wv|vww|ww|vvv|v|w|vvvvvvwvyvvvy|ww||v|wvv|v|vwvw|vv||vvwvv||wv||vwvy|v|vwwv|w|||wvwwwwwvw|wv|v|vvwwvv||vw||wv|wvvyvvwvwv||yvv|w|vv||vwvvwv||wvvv|v||vv|v|||ywyw||vv|w|||w||v|v|vvvy|wvvv||w|www|vv||www|w|w|ww|vvww||vwvv|vv||wwvvwwwvv|wwv||||vwv||w|wwwvvw||v|v|w|wv|vw||vy||vvwyvw|yvvvv|vvvvvw|vvvy|vvwvv|vvw||w|wv|www|ywvvwvvw||ww|vvv|wvvv||vvvvvy|wv|ww|vv|wv|wyv|vwwv|wvwvvwvyww|w|wvv||www|w|w||v|www|||vv|vwv|yw||ww||wwvv|vv||wwwvvwvvwvvv|ww||vw||vvwwwvwwvw|vvww|v|vv|vyvw|wvyv|w|vv|v|v|vv|w|y|v|vw|vvwvvw|vvvvyvvvwvvw|w|vwywwy|vw|vw|vvvwww|wwww|v|ww|ww|vvvw||wyvwvwvvvwv|wv||yw||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| \ No newline at end of file diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.prx b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.prx deleted file mode 100644 index d258335..0000000 Binary files a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.prx and /dev/null differ diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.tii b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.tii deleted file mode 100644 index ddc96f2..0000000 Binary files a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.tii and /dev/null differ diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.tis b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.tis deleted file mode 100644 index dbedb62..0000000 Binary files a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/_1r.tis and /dev/null differ diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/segments.gen b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/segments.gen deleted file mode 100644 index c17e7df..0000000 Binary files a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/segments.gen and /dev/null differ diff --git a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/segments_1s b/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/segments_1s deleted file mode 100644 index c235797..0000000 Binary files a/all_code/.recommenders/index/http___download_eclipse_org_recommenders_models_neon_/segments_1s and /dev/null differ diff --git a/all_code/NumberParser/.classpath b/all_code/NumberParser/.classpath deleted file mode 100644 index cee56e4..0000000 --- a/all_code/NumberParser/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/all_code/NumberParser/.project b/all_code/NumberParser/.project deleted file mode 100644 index 4e4fb7c..0000000 --- a/all_code/NumberParser/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - NumberParser - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/all_code/NumberParser/.settings/org.eclipse.jdt.core.prefs b/all_code/NumberParser/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 3a21537..0000000 --- a/all_code/NumberParser/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,11 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/all_code/NumberParser/META-INF/MANIFEST.MF b/all_code/NumberParser/META-INF/MANIFEST.MF deleted file mode 100644 index 0cc1cc2..0000000 --- a/all_code/NumberParser/META-INF/MANIFEST.MF +++ /dev/null @@ -1,9 +0,0 @@ -Manifest-Version: 1.0 -Created-By: varocarbas -Implementation-Title: NumberParser -Implementation-Version: 1.0.8.5 -Implementation-Vendor: Custom Solvers 2.0 -Implementation-URL: https://customsolvers.com/number_parser_java/ -Specification-Title: NumberParser -Specification-Version: 1.0.8.5 -Specification-Vendor: Custom Solvers 2.0 diff --git a/all_code/NumberParser/build.xml b/all_code/NumberParser/build.xml deleted file mode 100644 index 62a0b97..0000000 --- a/all_code/NumberParser/build.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Basic.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Basic.java deleted file mode 100644 index 1cac00a..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Basic.java +++ /dev/null @@ -1,121 +0,0 @@ -package InternalNumberParser; - -import InternalNumberParser.CSharpAdaptation.*; -import NumberParser.*; -import NumberParser.Number; - -import java.util.ArrayList; -import java.util.HashMap; - -@SuppressWarnings({ "rawtypes", "unchecked", "serial" }) -public class Basic -{ - //Positive min./max. values for all the supported numeric types to behave accurately. - //This is useful when dealing with NumberX variables, to determine the points where BaseTenExponent - //has to be brought into picture to complement Value. - public static HashMap> AllNumberMinMaxPositives = - new HashMap>() - { - { - put(NumericTypes.Double, new ArrayList() {{ add(1e-308); add(Double.MAX_VALUE); }}); - put(NumericTypes.Float, new ArrayList() {{ add(1e-37); add(Float.MAX_VALUE); }}); - put(NumericTypes.Long, new ArrayList() {{ add(1); add(Long.MAX_VALUE); }}); - put(NumericTypes.Integer, new ArrayList() {{ add(1); add(Integer.MAX_VALUE); }}); - put(NumericTypes.Short, new ArrayList() {{ add(1); add(Short.MAX_VALUE); }}); - put(NumericTypes.Character, new ArrayList() {{ add(1); add(Character.MAX_VALUE); }}); - put(NumericTypes.Byte, new ArrayList() {{ add(1); add(Byte.MAX_VALUE); }}); - } - }; - - //Min./max. values for all the supported numeric types. - public static HashMap> AllNumberMinMaxs = - new HashMap>() - { - { - put(NumericTypes.Double, new ArrayList() {{ add(Double.MIN_VALUE); add(Double.MAX_VALUE); }}); - put(NumericTypes.Float, new ArrayList() {{ add(Float.MIN_VALUE); add(Float.MAX_VALUE); }}); - put(NumericTypes.Long, new ArrayList() {{ add(Long.MIN_VALUE); add(Long.MAX_VALUE); }}); - put(NumericTypes.Integer, new ArrayList() {{ add(Integer.MIN_VALUE); add(Integer.MAX_VALUE); }}); - put(NumericTypes.Short, new ArrayList() {{ add(Short.MIN_VALUE); add(Short.MAX_VALUE); }}); - put(NumericTypes.Character, new ArrayList() {{ add(Character.MIN_VALUE); add(Character.MAX_VALUE); }}); - put(NumericTypes.Byte, new ArrayList() {{ add(Byte.MIN_VALUE); add(Byte.MAX_VALUE); }}); - } - }; - - public static ArrayList AllNumericTypes = new ArrayList() - {{ - add(NumericTypes.Double); add(NumericTypes.Float); add(NumericTypes.Long); add(NumericTypes.Integer); - add(NumericTypes.Short); add(NumericTypes.Character); add(NumericTypes.Byte); - }}; - - public static ArrayList AllUnsignedTypes = new ArrayList() - {{ - add(NumericTypes.Byte); add(NumericTypes.Character); - }}; - - public static ArrayList AllNumberClassTypes = new ArrayList() - {{ - add(Number.class); add(NumberD.class); add(NumberO.class); add(NumberP.class); - }}; - - public static ArrayList AllDecimalTypes = new ArrayList() - {{ - add(NumericTypes.Double); add(NumericTypes.Float); - }}; - - //Returns all the types whose ranges are equal or smaller than int. - public static ArrayList GetSmallIntegers() - { - return LinqNP.Where - ( - AllNumericTypes, - ( - x -> x != NumericTypes.Long && - !AllDecimalTypes.contains(x) - ) - ); - } - - //The purpose of this function is to easily create simple values for a given type. - //It isn't prepared to deal with range incompatibilities between different types. - //Sample inputs: 0, 1 or -1. - public static Object GetNumberSpecificType(Object value, NumericTypes target) - { - NumericTypes type = ErrorInfoNumber.InputTypeIsValidNumeric(value); - if (type.equals(NumericTypes.None) || type.equals(target)) return value; - - return Conversions.CastDynamicToType(value, target); - } - - //This method assumes that input and type are valid numeric types. - public static boolean InputInsideTypeRange(Object input, NumericTypes type) - { - double value = Conversions.ConvertToDoubleInternal - ( - new NumberD(input).getValue() - ); - - ArrayList minMax = new ArrayList() - {{ - add - ( - ConvertTo.ConverToDouble - ( - Basic.AllNumberMinMaxPositives.get(type).get(0) - ) - ); - add - ( - ConvertTo.ConverToDouble - ( - Basic.AllNumberMinMaxPositives.get(type).get(1) - ) - ); - }}; - - return - ( - value >= minMax.get(0) && value <= minMax.get(1) - ); - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/CSharpOtherNP.java b/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/CSharpOtherNP.java deleted file mode 100644 index ea6d418..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/CSharpOtherNP.java +++ /dev/null @@ -1,597 +0,0 @@ -package InternalNumberParser.CSharpAdaptation; - -import java.util.ArrayList; -import java.util.Locale; - -import InternalNumberParser.*; -import InternalNumberParser.Operations.OperationsOther; -import NumberParser.*; -import NumberParser.Number; - -@SuppressWarnings("serial") -public class CSharpOtherNP -{ - //Method delivering the most adequate NumberD instance by eventually compensating the - //Java/C# differences on the implicit conversion of numeric types front. - public static NumberD ExtractValueAndTypeInfo(Object value, int baseTenExponent, NumericTypes type) - { - NumericTypes typeValue = ErrorInfoNumber.InputTypeIsValidNumeric(value); - if (typeValue.equals(NumericTypes.None)) - { - return new NumberD(ErrorTypesNumber.InvalidInput); - } - - return - ( - typeValue.equals(type) ? new NumberD(value, baseTenExponent) : - (NumberD)OperationsOther.VaryBaseTenExponent - ( - Conversions.ConvertNumberToAny - ( - Conversions.ConvertAnyValueToDouble(value), type - ), - baseTenExponent - ) - ); - } - - public static String SpecificDoubleOrNumberXToString(Object input, Locale culture) - { - if (input == null) return ""; - - NumericTypes type = NumericTypesMethods.GetTypeFromObject - ( - input - ); - - return - ( - !type.equals(NumericTypes.None) ? NumericValueToString - ( - Conversions.ConvertTargetToDouble - ( - input - ) - , culture, type - ) - : SpecificNumberXToString(input, culture) - ); - } - - public static String SpecificNumberXToString(Object input) - { - return SpecificNumberXToString(input, Locale.US); - } - - static String SpecificNumberXToString(Object input, Locale culture) - { - if (input == null) return null; - - if (input.getClass().equals(Number.class)) - { - return ((Number)input).toString(culture); - } - else if (input.getClass().equals(NumberD.class)) - { - return ((NumberD)input).toString(culture); - } - else if (input.getClass().equals(NumberO.class)) - { - return ((NumberO)input).toString(culture); - } - else if (input.getClass().equals(NumberP.class)) - { - return ((NumberP)input).toString(culture); - } - - return null; - } - - //Method emulating the .NET numeric-type ToString() method by focusing on the three - //categories which are relevant here: decimal/exponential, integer and character. - public static String NumericValueToString(Object input, Locale culture, NumericTypes type) - { - Object input2 = input; - - NumericTypes type0 = NumericTypesMethods.GetTypeFromObject(input); - if (!type0.equals(type)) - { - input2 = CSharpOtherNP.CastConvertNumericObjectToTarget(input, type); - } - - if (type.equals(NumericTypes.Character)) - { - return ((Character)input2).toString(); - } - - return - ( - Basic.AllDecimalTypes.contains(type) ? - DecimalTypeToString(input2, culture, type) : - IntegerTypeToString(input2, type) - ); - } - - //This method expects a valid instance of any integer numeric type except Character. - static String IntegerTypeToString(Object input, NumericTypes type) - { - Long input2 = 0l; - - if (type.equals(NumericTypes.Long)) - { - input2 = (long)input; - } - else if (type.equals(NumericTypes.Integer)) - { - input2 = ((Integer)input).longValue(); - } - else if (type.equals(NumericTypes.Short)) - { - input2 = ((Short)input).longValue(); - } - else if (type.equals(NumericTypes.Byte)) - { - input2 = ((Byte)input).longValue(); - } - - return input2.toString(); - } - - //This method expects a valid instance of any decimal numeric type except. - static String DecimalTypeToString(Object input, Locale culture, NumericTypes type) - { - String format = "%.12e"; - double input2 = 0.0; - - if (type.equals(NumericTypes.Double)) - { - input2 = (double)input; - } - else - { - input2 = ((Float)input).doubleValue(); - } - - if - ( - input2 == 0.0 || - ( - input2 >= 0.0000001 && - input2 <= 1000000 - ) - ) - { format = "%s"; } - - return - ( - culture == null ? String.format(format, input) : - String.format(culture, format, input) - ); - } - - public static ArrayList SplitTryCatch(String input, String separator) - { - if (input == null || separator == null) - { - return new ArrayList() - {{ - add(input); - }}; - } - - try - { - return ArrayToArrayList - ( - input.split(separator) - ); - } - catch(Exception e) { } - - return new ArrayList() - {{ - add(input); - }}; - } - - public static String Substring(String input, int startI, int length) - { - return - ( - length < 0 ? input.substring(startI) : - input.substring(startI, startI + length) - ); - } - - public static ArrayList SplitTryCatchMulti(String input, ArrayList separators) - { - ArrayList output = new ArrayList() - {{ - add(input); - }}; - - if (input == null || separators == null || separators.size() < 1) - { - return output; - } - - for (String separator: separators) - { - for (int i = output.size() - 1; i >= 0; i--) - { - ArrayList tempArray = SplitTryCatch - ( - output.get(i), separator - ); - - if (tempArray.size() > 1) - { - output.remove(i); - output.addAll(i, tempArray); - } - } - } - - return output; - } - - public static ArrayList StringToCharacters(String input) - { - ArrayList chars = new ArrayList(); - if (input == null) return chars; - - for (char item: input.toCharArray()) - { - chars.add(item); - } - - return chars; - } - - static ArrayList ArrayToArrayList(X[] input) - { - ArrayList output = new ArrayList(); - - for (X item: input) - { - output.add(item); - } - - return output; - } - - public static String StringJoin(String separator, ArrayList parts) - { - return StringJoinInternal - ( - separator, parts, null, 0, parts.size() - ); - } - - static String StringJoinInternal - ( - String separator, ArrayList parts, - ArrayList parts2, int start, int length - ) - { - if (parts == null && parts2 == null) return null; - - int total = - ( - parts == null ? parts2.size() : parts.size() - ); - if (total == 1) - { - return - ( - parts == null ? parts2.get(0).toString() : parts.get(0) - ); - } - - String outString = StringJoinInternalBit(parts, parts2, start, ""); - - for (int i = start + 1; i < length; i++) - { - outString += StringJoinInternalBit(parts, parts2, i, separator); - } - - return outString; - } - - static String StringJoinInternalBit - ( - ArrayList parts, ArrayList parts2, int i, String separator - ) - { - String bit = ""; - - if (parts == null) - { - if (parts2.size() >= i - 1) - { - bit = parts2.get(i).toString(); - } - } - else if (parts.size() >= i - 1) - { - bit = parts.get(i); - } - - return separator + bit; - } - - public static Object CastConvertNumericObjectToTarget(Object input, NumericTypes target) - { - NumericTypes type0 = NumericTypesMethods.GetTypeFromObject(input); - if (type0.equals(NumericTypes.None)) return input; - - if (type0.equals(NumericTypes.Double)) - { - return ConvertDoubleToTarget((double)input, target); - } - else if (type0.equals(NumericTypes.Float)) - { - return ConvertFloatToTarget((float)input, target); - } - else if (type0.equals(NumericTypes.Long)) - { - return ConvertLongToTarget((long)input, target); - } - else if (type0.equals(NumericTypes.Integer)) - { - return ConvertIntegerToTarget((int)input, target); - } - else if (type0.equals(NumericTypes.Short)) - { - return ConvertShortToTarget((short)input, target); - } - else if (type0.equals(NumericTypes.Byte)) - { - return ConvertByteToTarget((byte)input, target); - } - else if (type0.equals(NumericTypes.Character)) - { - return ConvertCharacterToTarget((char)input, target); - } - - return input; - } - - public static Object ConvertCharacterToTarget(Character value, NumericTypes type) - { - if (type.equals(NumericTypes.Character)) return value; - - Integer value2 = new Integer(value); - - if (type.equals(NumericTypes.Double)) - { - return value2.doubleValue(); - } - else if (type.equals(NumericTypes.Float)) - { - return value2.floatValue(); - } - else if (type.equals(NumericTypes.Long)) - { - return value2.longValue(); - } - else if (type.equals(NumericTypes.Integer)) - { - return value2.intValue(); - } - else if (type.equals(NumericTypes.Short)) - { - return value2.shortValue(); - } - else if (type.equals(NumericTypes.Byte)) - { - return value2.byteValue(); - } - - return 0; - } - - public static Object ConvertByteToTarget(Byte value, NumericTypes type) - { - if (type.equals(NumericTypes.Double)) - { - return value.doubleValue(); - } - else if (type.equals(NumericTypes.Float)) - { - return value.byteValue(); - } - else if (type.equals(NumericTypes.Long)) - { - return value.longValue(); - } - else if (type.equals(NumericTypes.Integer)) - { - return value.intValue(); - } - else if (type.equals(NumericTypes.Short)) - { - return value.shortValue(); - } - else if (type.equals(NumericTypes.Byte)) - { - return value; - } - else if (type.equals(NumericTypes.Character)) - { - return (char)(value.intValue()); - } - - return 0; - } - - public static Object ConvertShortToTarget(Short value, NumericTypes type) - { - if (type.equals(NumericTypes.Double)) - { - return value.doubleValue(); - } - else if (type.equals(NumericTypes.Float)) - { - return value.floatValue(); - } - else if (type.equals(NumericTypes.Long)) - { - return value.longValue(); - } - else if (type.equals(NumericTypes.Integer)) - { - return value.intValue(); - } - else if (type.equals(NumericTypes.Short)) - { - return value; - } - else if (type.equals(NumericTypes.Byte)) - { - return value.byteValue(); - } - else if (type.equals(NumericTypes.Character)) - { - return (char)(value.intValue()); - } - - return 0; - } - - public static Object ConvertIntegerToTarget(Integer value, NumericTypes type) - { - if (type.equals(NumericTypes.Double)) - { - return value.doubleValue(); - } - else if (type.equals(NumericTypes.Float)) - { - return value.floatValue(); - } - else if (type.equals(NumericTypes.Long)) - { - return value.longValue(); - } - else if (type.equals(NumericTypes.Integer)) - { - return value; - } - else if (type.equals(NumericTypes.Short)) - { - return value.shortValue(); - } - else if (type.equals(NumericTypes.Byte)) - { - return value.byteValue(); - } - else if (type.equals(NumericTypes.Character)) - { - return (char)(value.intValue()); - } - - return 0; - } - - public static Object ConvertLongToTarget(Long value, NumericTypes type) - { - if (type.equals(NumericTypes.Double)) - { - return value.doubleValue(); - } - else if (type.equals(NumericTypes.Float)) - { - return value.floatValue(); - } - else if (type.equals(NumericTypes.Long)) - { - return value; - } - else if (type.equals(NumericTypes.Integer)) - { - return value.intValue(); - } - else if (type.equals(NumericTypes.Short)) - { - return value.shortValue(); - } - else if (type.equals(NumericTypes.Byte)) - { - return value.byteValue(); - } - else if (type.equals(NumericTypes.Character)) - { - return (char)(value.intValue()); - } - - return 0; - } - - public static Object ConvertFloatToTarget(Float value, NumericTypes type) - { - if (type.equals(NumericTypes.Double)) - { - return value.doubleValue(); - } - else if (type.equals(NumericTypes.Float)) - { - return value; - } - else if (type.equals(NumericTypes.Long)) - { - return value.longValue(); - } - else if (type.equals(NumericTypes.Integer)) - { - return value.intValue(); - } - else if (type.equals(NumericTypes.Short)) - { - return value.shortValue(); - } - else if (type.equals(NumericTypes.Byte)) - { - return value.byteValue(); - } - else if (type.equals(NumericTypes.Character)) - { - return (char)(value.intValue()); - } - - return 0; - } - - public static Object ConvertDoubleToTarget(Double value, NumericTypes type) - { - if (type.equals(NumericTypes.Double)) - { - return value; - } - else if (type.equals(NumericTypes.Float)) - { - return value.floatValue(); - } - else if (type.equals(NumericTypes.Long)) - { - return value.longValue(); - } - else if (type.equals(NumericTypes.Integer)) - { - return value.intValue(); - } - else if (type.equals(NumericTypes.Short)) - { - return value.shortValue(); - } - else if (type.equals(NumericTypes.Byte)) - { - return value.byteValue(); - } - else if (type.equals(NumericTypes.Character)) - { - return (char)(value.intValue()); - } - - return 0; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/CompareNumeric.java b/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/CompareNumeric.java deleted file mode 100644 index 99f3052..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/CompareNumeric.java +++ /dev/null @@ -1,237 +0,0 @@ -package InternalNumberParser.CSharpAdaptation; - -import InternalNumberParser.Conversions; -import NumberParser.*; - -public class CompareNumeric -{ - public static boolean FirstGreaterOrEqual(Object first, Object second, NumericTypes type) - { - if (first == null || second == null) - { - return - ( - CompareToNulls(first, second) <= 0 - ); - } - - if (type.equals(NumericTypes.Double)) - { - return - ( - CompareToDouble(first, second) <= 0 - ); - } - else if (type.equals(NumericTypes.Float)) - { - return - ( - CompareToFloat(first, second) <= 0 - ); - } - else if (type.equals(NumericTypes.Long)) - { - return - ( - CompareToLong(first, second) <= 0 - ); - } - else if (type.equals(NumericTypes.Integer)) - { - return - ( - CompareToInteger(first, second) <= 0 - ); - } - else if (type.equals(NumericTypes.Short)) - { - return - ( - CompareToShort(first, second) <= 0 - ); - } - else if (type.equals(NumericTypes.Byte)) - { - return - ( - CompareToByte(first, second) <= 0 - ); - } - else if (type.equals(NumericTypes.Character)) - { - return - ( - CompareToCharacter(first, second) <= 0 - ); - } - - return false; - } - - public static boolean BothEqual(Object first, Object second, NumericTypes type) - { - if (first == null || second == null) - { - return - ( - CompareToNulls(first, second) == 0 - ); - } - - if (type.equals(NumericTypes.Double)) - { - return - ( - CompareToDouble(first, second) == 0 - ); - } - else if (type.equals(NumericTypes.Float)) - { - return - ( - CompareToFloat(first, second) == 0 - ); - } - else if (type.equals(NumericTypes.Long)) - { - return - ( - CompareToLong(first, second) == 0 - ); - } - else if (type.equals(NumericTypes.Integer)) - { - return - ( - CompareToInteger(first, second) == 0 - ); - } - else if (type.equals(NumericTypes.Short)) - { - return - ( - CompareToShort(first, second) == 0 - ); - } - else if (type.equals(NumericTypes.Byte)) - { - return - ( - CompareToByte(first, second) == 0 - ); - } - else if (type.equals(NumericTypes.Character)) - { - return - ( - CompareToCharacter(first, second) == 0 - ); - } - - return false; - } - - static int CompareToNulls(Object first, Object second) - { - int output = 0; - - if (first == null) - { - output = (second == null ? 0 : 1); - } - else if (second == null) output = -1; - - return output; - } - - public static int CompareToDouble(Object first, Object second) - { - if (first == null || second == null) - { - return CompareToNulls(first, second); - } - - Double first2 = Conversions.ConvertTargetToDouble(first); - Double second2 = Conversions.ConvertTargetToDouble(second); - - return first2.compareTo(second2); - } - - public static int CompareToFloat(Object first, Object second) - { - if (first == null || second == null) - { - return CompareToNulls(first, second); - } - - Float first2 = (Float)first; - Float second2 = (Float)second; - - return first2.compareTo(second2); - } - - public static int CompareToLong(Object first, Object second) - { - if (first == null || second == null) - { - return CompareToNulls(first, second); - } - - Long first2 = (Long)first; - Long second2 = (Long)second; - - return first2.compareTo(second2); - } - - public static int CompareToInteger(Object first, Object second) - { - if (first == null || second == null) - { - return CompareToNulls(first, second); - } - - Integer first2 = (Integer)first; - Integer second2 = (Integer)second; - - return first2.compareTo(second2); - } - - public static int CompareToShort(Object first, Object second) - { - if (first == null || second == null) - { - return CompareToNulls(first, second); - } - - Short first2 = (Short)first; - Short second2 = (Short)second; - - return first2.compareTo(second2); - } - - public static int CompareToByte(Object first, Object second) - { - if (first == null || second == null) - { - return CompareToNulls(first, second); - } - - Byte first2 = (Byte)first; - Byte second2 = (Byte)second; - - return first2.compareTo(second2); - } - - public static int CompareToCharacter(Object first, Object second) - { - if (first == null || second == null) - { - return CompareToNulls(first, second); - } - - Character first2 = (Character)first; - Character second2 = (Character)second; - - return first2.compareTo(second2); - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/ConvertTo.java b/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/ConvertTo.java deleted file mode 100644 index 14000eb..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/ConvertTo.java +++ /dev/null @@ -1,47 +0,0 @@ -package InternalNumberParser.CSharpAdaptation; - -import NumberParser.*; - -public class ConvertTo -{ - public static double ConverToDouble(Object input) - { - if (input == null) return Double.NaN; - - NumericTypes type = - NumericTypesMethods.GetTypeFromObject - ( - input - ); - if (type.equals(NumericTypes.Float)) - { - return ((Float)input).doubleValue(); - } - else if (type.equals(NumericTypes.Long)) - { - return ((Long)input).doubleValue(); - } - else if (type.equals(NumericTypes.Integer)) - { - return ((Integer)input).doubleValue(); - } - else if (type.equals(NumericTypes.Short)) - { - return ((Short)input).doubleValue(); - } - else if (type.equals(NumericTypes.Byte)) - { - return ((Byte)input).doubleValue(); - } - else if (type.equals(NumericTypes.Character)) - { - return new Integer - ( - Character.getNumericValue((char)input) - ) - .doubleValue(); - } - - return 0.0; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/LinqNP.java b/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/LinqNP.java deleted file mode 100644 index 1756264..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/LinqNP.java +++ /dev/null @@ -1,84 +0,0 @@ -package InternalNumberParser.CSharpAdaptation; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -//Class including Java custom versions for all the System.Linq methods used in the original C# code. -public class LinqNP -{ - public static ArrayList Select(ArrayList input, Function filter) - { - if (input == null || filter == null) return null; - - return (ArrayList)input.stream().map(filter).collect(Collectors.toList()); - } - - public static ArrayList Where(ArrayList input, Predicate filter) - { - if (input == null || filter == null) return input; - - try - { - return (ArrayList)input.stream().filter(filter).collect - ( - Collectors.toList() - ); - } - catch(Exception e) { } - - return input; - } - - public static X FirstOrDefault(ArrayList input, X defaultVal) - { - return FirstOrDefault(input, null, defaultVal); - } - - public static X FirstOrDefault(ArrayList input, Predicate filter, X defaultVal) - { - if (input == null) return defaultVal; - - return GetFirst - ( - new ArrayList(Where(input, filter)), defaultVal - ); - } - - static X GetFirst(ArrayList input, X defaultVal) - { - if (input == null) return defaultVal; - - try - { - for (X item : input) - { - return item; - } - } - catch (Exception e) { } - - return defaultVal; - } - - public static ArrayList OrderByDescending(ArrayList input, Comparator comparator) - { - return PerformSorting(input, comparator, false); - } - - static ArrayList PerformSorting(ArrayList input, Comparator comparator, boolean ascending) - { - if (input == null || comparator == null) return input; - - ArrayList output = new ArrayList(input); - if (output.size() < 2) return output; - - output.sort(comparator); - if (!ascending) Collections.reverse(output); - - return output; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/NumberX.java b/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/NumberX.java deleted file mode 100644 index 97a8d9e..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/NumberX.java +++ /dev/null @@ -1,75 +0,0 @@ -package InternalNumberParser.CSharpAdaptation; - -import NumberParser.*; -import NumberParser.Number; - -//This class is meant to somehow account for the implicit conversions among all the NumberX classes -//in the original C# code. -@SuppressWarnings("rawtypes") -public class NumberX -{ - public enum NumberXTypes { None, Number, NumberD, NumberO, NumberP } - - public static class MainVars - { - public int BaseTenExponent; - public Object Value; - public ErrorTypesNumber Error; - public NumberXTypes Type = NumberXTypes.None; - } - - public static MainVars GetMainVars(Object numberX) - { - return - ( - numberX == null ? new MainVars() : GetMainVars - ( - numberX, numberX.getClass() - ) - ); - } - - public static MainVars GetMainVars(Object numberX, Class type) - { - MainVars output = new MainVars(); - - if (type.equals(Number.class)) - { - Number numberX2 = (Number)numberX; - - output.Type = NumberXTypes.Number; - output.Value = numberX2.getValue(); - output.BaseTenExponent = numberX2.getBaseTenExponent(); - output.Error = numberX2.getError(); - } - else if (type.equals(NumberD.class)) - { - NumberD numberX2 = (NumberD)numberX; - - output.Type = NumberXTypes.NumberD; - output.Value = numberX2.getValue(); - output.BaseTenExponent = numberX2.getBaseTenExponent(); - output.Error = numberX2.getError(); - } - else if (type.equals(NumberO.class)) - { - NumberO numberX2 = (NumberO)numberX; - - output.Type = NumberXTypes.NumberO; - output.Value = numberX2.getValue(); - output.BaseTenExponent = numberX2.getBaseTenExponent(); - output.Error = numberX2.getError(); - } - else if (type.equals(NumberP.class)) - { - NumberP numberX2 = (NumberP)numberX; - - output.Type = NumberXTypes.NumberP; - output.Value = numberX2.getValue(); - output.BaseTenExponent = numberX2.getBaseTenExponent(); - output.Error = numberX2.getError(); - } - - return output; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/SystemMath.java b/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/SystemMath.java deleted file mode 100644 index ea161c3..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/SystemMath.java +++ /dev/null @@ -1,19 +0,0 @@ -package InternalNumberParser.CSharpAdaptation; - -import NumberParser.*; - -//Class including emulations of the .NET in-built System.Math methods used at some point of the code by relying -//on the corresponding System.Math2 versions. -public class SystemMath -{ - public static RoundType GetNewRoundItemFromExisting(MidpointRounding input) - { - return - ( - input.equals(MidpointRounding.ToEven) - ? RoundType.MidpointToEven - : RoundType.MidpointAwayFromZero - ); - } -} - diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/TryParseMethodsNP.java b/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/TryParseMethodsNP.java deleted file mode 100644 index efa05f6..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/TryParseMethodsNP.java +++ /dev/null @@ -1,193 +0,0 @@ -package InternalNumberParser.CSharpAdaptation; - -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Locale; - -import NumberParser.NumericTypes; - -public class TryParseMethodsNP -{ - public static TryParseOutputNP Double(String input, Locale culture) - { - return DecimalType - ( - input, culture, NumericTypes.Double - ); - } - - public static TryParseOutputNP Float(String input, Locale culture) - { - return DecimalType - ( - input, culture, NumericTypes.Float - ); - } - - public static TryParseOutputNP DecimalType - ( - String input, Locale culture, NumericTypes numericType - ) - { - TryParseOutputNP output = new TryParseOutputNP(); - - try - { - boolean isWrong = false; - Number number = ParseCommon(input, culture); - output.IsOK = true; - - if (numericType.equals(NumericTypes.Double)) - { - output.DoubleVal = number.doubleValue(); - Double val = new Double(output.DoubleVal); - - if (val.isNaN() || val.isInfinite()) - { - isWrong = true; - } - } - else if (numericType.equals(NumericTypes.Float)) - { - output.FloatVal = number.floatValue(); - Float val = new Float(output.FloatVal); - - if (val.isNaN() || val.isInfinite()) - { - isWrong = true; - } - } - - if (input != null && (input.contains("e") || isWrong)) - { - ArrayList tempVar = CSharpOtherNP.SplitTryCatch - ( - input.toLowerCase(), "e" - ); - - if (tempVar.size() == 2) - { - if - ( - LinqNP.FirstOrDefault - ( - CSharpOtherNP.StringToCharacters - ( - tempVar.get(1) - ), - x -> !Character.isDigit(x), '\u0000' - ) - != '\u0000' - ) - { - //Emulating the conditions of the original C# version which doesn't support decimal exponents. - output.IsOK = false; - } - } - } - } - catch (Exception e) { output.IsOK = false; } - - return output; - } - - public static TryParseOutputNP Integer(String input, Locale culture) - { - return IntegerType - ( - input, culture, NumericTypes.Integer - ); - } - - public static TryParseOutputNP Long(String input, Locale culture) - { - return IntegerType - ( - input, culture, NumericTypes.Long - ); - } - - public static TryParseOutputNP Short(String input, Locale culture) - { - return IntegerType - ( - input, culture, NumericTypes.Short - ); - } - - public static TryParseOutputNP Byte(String input, Locale culture) - { - return IntegerType - ( - input, culture, NumericTypes.Byte - ); - } - - public static TryParseOutputNP Character(String input, Locale culture) - { - return IntegerType - ( - input, culture, NumericTypes.Character - ); - } - - static TryParseOutputNP IntegerType(String input, Locale culture, NumericTypes numericType) - { - TryParseOutputNP output = new TryParseOutputNP(); - - try - { - Number number = ParseCommon(input, culture); - - if (numericType.equals(NumericTypes.Long)) - { - output.LongVal = number.longValue(); - } - else if (numericType.equals(NumericTypes.Integer)) - { - output.IntegerVal = number.intValue(); - } - else if (numericType.equals(NumericTypes.Short)) - { - output.ShortVal = number.shortValue(); - } - else if (numericType.equals(NumericTypes.Byte)) - { - output.ByteVal = number.byteValue(); - } - else if (numericType.equals(NumericTypes.Character)) - { - output.CharacterVal = (char)number.intValue(); - } - - output.IsOK = true; - } - catch (Exception e) { } - - return output; - } - - static Number ParseCommon(String input, Locale culture) throws Exception - { - if - ( - input == null || LinqNP.FirstOrDefault - ( - CSharpOtherNP.StringToCharacters(input.toLowerCase()), - x -> !Character.isDigit(x) && - x != '.' && x != ',' && x != '-' && x != '+', '\u0000' - ) - != '\u0000' - ) - { - //This is required to ensure a full compatibility with the behaviour of the original C# version. - throw new Exception(); - } - - return NumberFormat.getInstance - ( - culture != null ? culture : Locale.US - ) - .parse(input); - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/TryParseOutputNP.java b/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/TryParseOutputNP.java deleted file mode 100644 index 870e8a8..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/CSharpAdaptation/TryParseOutputNP.java +++ /dev/null @@ -1,14 +0,0 @@ -package InternalNumberParser.CSharpAdaptation; - -public class TryParseOutputNP -{ - public boolean IsOK = false; - - public double DoubleVal = 0.0; - public float FloatVal = 0.0f; - public long LongVal = 0; - public int IntegerVal = 0; - public short ShortVal = 0; - public byte ByteVal = 0; - public char CharacterVal = '\0'; -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Constructors.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Constructors.java deleted file mode 100644 index 430cdf1..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Constructors.java +++ /dev/null @@ -1,87 +0,0 @@ -package InternalNumberParser; - -import NumberParser.*; -import NumberParser.Number; -import InternalNumberParser.CSharpAdaptation.*; - -@SuppressWarnings("rawtypes") -public class Constructors -{ - public static Object InitialiseNumberX(Class type, Object value, int baseTenExponent) - { - if (type.equals(Number.class)) - { - return new Number - ( - Conversions.ConvertTargetToDouble(value), baseTenExponent - ); - } - else if (type.equals(NumberD.class)) - { - return new NumberD(value, baseTenExponent); - } - else if (type.equals(NumberO.class)) - { - return new NumberO - ( - Conversions.ConvertTargetToDouble(value), baseTenExponent - ); - } - else if (type.equals(NumberP.class)) - { - return new NumberP(value, baseTenExponent); - } - - return null; - } - - //This method expects numberX to be a valid NumberX type - //(i.e., Number, NumberD, NumberO or NumberP). - public static Number ExtractDynamicToNumber(Object numberX) - { - if (numberX == null) - { - return new Number(ErrorTypesNumber.InvalidInput); - } - - NumberX.MainVars mainVars = NumberX.GetMainVars(numberX); - - if (!mainVars.Error.equals(ErrorTypesNumber.None)) - { - return new Number(mainVars.Error); - } - - return new Number - ( - Conversions.ConvertTargetToDouble - ( - mainVars.Value - ), - mainVars.BaseTenExponent - ); - } - - //This method expects numberX to be a valid NumberX type - //(i.e., Number, NumberD, NumberO or NumberP). - public static NumberD ExtractDynamicToNumberD(Object numberX) - { - if (numberX == null) - { - return new NumberD(ErrorTypesNumber.InvalidInput); - } - - NumberX.MainVars mainVars = NumberX.GetMainVars(numberX); - - if (!mainVars.Error.equals(ErrorTypesNumber.None)) - { - return new NumberD(mainVars.Error); - } - - NumberD output = new NumberD(); - - output.setValue(mainVars.Value); - output.setBaseTenExponent(mainVars.BaseTenExponent); - - return output; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Conversions.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Conversions.java deleted file mode 100644 index c1a6ca1..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Conversions.java +++ /dev/null @@ -1,396 +0,0 @@ -package InternalNumberParser; - -import NumberParser.*; -import NumberParser.Number; -import InternalNumberParser.CSharpAdaptation.*; -import InternalNumberParser.Operations.*; - -import java.util.ArrayList; - -@SuppressWarnings("serial") -public class Conversions -{ - public static NumberD ConvertNumberToAny(Number number, NumericTypes target) - { - ErrorTypesNumber error = ErrorInfoNumber.GetConvertToAnyError(number, target); - if (!error.equals(ErrorTypesNumber.None)) return new NumberD(error); - - NumberD outNumber = new NumberD(number); - ArrayList minMax = new ArrayList() - {{ - add - ( - ConvertToDoubleInternal - ( - Basic.AllNumberMinMaxs.get(target).get(0) - ) - ); - add - ( - ConvertToDoubleInternal - ( - Basic.AllNumberMinMaxs.get(target).get(1) - ) - ); - }}; - - if - ( - ConvertTargetToDouble(outNumber.getValue()) < minMax.get(0) || - ConvertTargetToDouble(outNumber.getValue()) > minMax.get(1) - ) - { - outNumber = new NumberD - ( - AdaptValueToTargetRange(outNumber, target, minMax) - ); - } - - outNumber.setValue - ( - CSharpOtherNP.ConvertDoubleToTarget - ( - ConvertTargetToDouble - ( - //This call to Math.round is required to emulate the in-built behaviour of - //the decimal type in the original C# version. - Math.round - ( - ConvertTargetToDouble - ( - outNumber.getValue() - ) - ) - ), - target - ) - ); - - return outNumber; - } - - private static Number AdaptValueToTargetRange(NumberD outNumber, NumericTypes target, ArrayList minMax) - { - double value = Conversions.ConvertTargetToDouble - ( - outNumber.getValue() - ); - if (value == 0.0) return new Number(outNumber); - - double targetValue = - ( - value < minMax.get(0) ? - minMax.get(0) : minMax.get(1) - ); - - if (value < 0.0 && Basic.AllUnsignedTypes.contains(target)) - { - outNumber.setValue(Math.abs(value)); - - if (value > minMax.get(1)) - { - //The resulting unsigned value (its absolute value, because the result of converting -123 - //to a zero-based scale is 123) is outside the range of the given type and that's it needs - //further adaptation. - targetValue = minMax.get(1); - } - else return new Number(outNumber); - } - - return ModifyValueToFitType - ( - new Number(outNumber), target, targetValue - ); - } - - static Number ModifyValueToFitType(Number number, NumericTypes target, double targetValue) - { - double sign = 1.0; - double value = number.getValue(); - - if (value < 0) - { - sign = -1.0; - number.setValue(value * sign); - } - - if (!Basic.AllDecimalTypes.contains(target)) - { - value = Conversions.ConvertTargetToDouble - ( - Math2.Round3 - ( - new NumberD(number), - MidpointRounding.AwayFromZero - ) - .getValue() - ); - } - else value = number.getValue(); - - targetValue = Math.abs(targetValue); - boolean increase = (value < targetValue); - int baseTenExponent = number.getBaseTenExponent(); - - //Apparently, the precision problems of the (Java) Double type appear more easily with - //divisions. That's why I am including here two variations: to rely on multiplications - //in all the possible scenarios. - double varMult = 10.0; - double varDiv = 0.1; - - while (true) - { - if (value == targetValue) break; - else - { - if (increase) - { - if - ( - value > (double)Basic.AllNumberMinMaxPositives.get - ( - NumericTypes.Double - ) - .get(1) * varDiv - ) - { break; } - - value *= varMult; - baseTenExponent--; - if (value > targetValue) break; - } - else - { - if - ( - value < (double)Basic.AllNumberMinMaxPositives.get - ( - NumericTypes.Double - ) - .get(0) * varMult - ) - { break; } - - value *= varDiv; - baseTenExponent++; - if (value < targetValue) break; - } - } - } - - value *= sign; - number.setValue(value); - number.setBaseTenExponent(baseTenExponent); - - return number; - } - - static double ConvertTargetToDoubleInternal(Object input, NumericTypes type) - { - if (type.equals(NumericTypes.Double)) - { - return (double)input; - } - else if (type.equals(NumericTypes.Float)) - { - return ((Float)input).doubleValue(); - } - else if (type.equals(NumericTypes.Long)) - { - return ((Long)input).doubleValue(); - } - else if (type.equals(NumericTypes.Integer)) - { - return ((Integer)input).doubleValue(); - } - else if (type.equals(NumericTypes.Short)) - { - return ((Short)input).doubleValue(); - } - else if (type.equals(NumericTypes.Byte)) - { - return ((Byte)input).doubleValue(); - } - else if (type.equals(NumericTypes.Character)) - { - return (new Integer((char)input)).doubleValue(); - } - - return Double.NaN; - } - - public static double ConvertTargetToDouble(Object input) - { - NumericTypes type = NumericTypesMethods.GetTypeFromObject(input); - - return - ( - type.equals(NumericTypes.None) ? 0.0 : - ConvertTargetToDoubleInternal(input, type) - ); - } - - //Note that double is used as a backup type in quite a few situations. - //This method complements the in-built Convert.ToDouble method by accounting for situations like - //char type variables. - public static double ConvertToDoubleInternal(Object value) - { - NumericTypes type = ErrorInfoNumber.InputTypeIsValidNumeric(value); - - return - ( - type.equals(NumericTypes.None) ? Double.NaN : - ConvertTargetToDoubleInternal(value, type) - ); - } - - //When calling methods with different overloads (e.g., some of the System.Math ones), - //the Object variables need to be cast to a specific type. - //This method assumes that input can be directly cast to the target numeric type. - //NOTE: due to the differences between Java and C# (language in which this method was - //created in the original code), all the casts are replaced with conversions. - public static Object CastDynamicToType(Object input, NumericTypes target) - { - return CSharpOtherNP.CastConvertNumericObjectToTarget(input, target); - } - - //This method assumes that numberD is a non-null valid NumberD variable. - public static Number ConvertNumberDToNumber(NumberD numberD) - { - Number outNumber = ConvertAnyValueToDouble(numberD.getValue()); - - return (Number)OperationsOther.VaryBaseTenExponent - ( - outNumber, numberD.getBaseTenExponent() - ); - } - - //This method assumes that both value and type refer to valid numeric types. - public static Number ConvertAnyValueToDouble(Object value) - { - if (ErrorInfoNumber.InputTypeIsValidNumeric(value).equals(NumericTypes.None)) - { - return new Number(ErrorTypesNumber.InvalidInput); - } - - Number output = new Number(); - output.setValue(ConvertToDoubleInternal(value)); - - return output; - } - - static Number ConvertFloatingToDouble2 - ( - Object value, NumericTypes type, Object[] minMax, - Object step, Number outNumber - ) - { - if (type.equals(NumericTypes.Double)) - { - double value2 = (double)value; - double step2 = (double)step; - double[] minMax2 = new double[] - { - (double)minMax[0], (double)minMax[1] - }; - - while (Math.abs(value2) < minMax2[0]) - { - outNumber.setBaseTenExponent - ( - outNumber.getBaseTenExponent() - 1 - ); - value2 *= step2; - }; - - while (Math.abs(value2) > minMax2[1]) - { - outNumber.setBaseTenExponent - ( - outNumber.getBaseTenExponent() + 1 - ); - value2 /= step2; - }; - - outNumber.setValue(value2); - } - else - { - float value2 = (float)value; - float step2 = (float)step; - float[] minMax2 = new float[] - { - (float)minMax[0], (float)minMax[1] - }; - - while (Math.abs(value2) < minMax2[0]) - { - outNumber.setBaseTenExponent - ( - outNumber.getBaseTenExponent() - 1 - ); - value2 *= step2; - }; - - while (Math.abs(value2) > minMax2[1]) - { - outNumber.setBaseTenExponent - ( - outNumber.getBaseTenExponent() + 1 - ); - value2 /= step2; - }; - - outNumber.setValue((double)value2); - } - - return outNumber; - } - - //This method expects value to be a valid double variable. - public static Number ConvertDoubleToNumber(double value) - { - Number outNumber = new Number(); - if (value == 0.0) return outNumber; - - double step = 10.0; - - double[] minMax = new double[] - { - (double)Basic.AllNumberMinMaxPositives.get - ( - NumericTypes.Double - ) - .get(0), (double)Basic.AllNumberMinMaxPositives.get - ( - NumericTypes.Double - ) - .get(1) - }; - - //Note that value can only be double or float and these types cannot provoke an overflow when - //using Math.Abs. Additionally, using Operations.AbsInternal right away isn't possible here - //because of provoking an infinite loop. - while (Math.abs(value) < minMax[0]) - { - outNumber.setBaseTenExponent - ( - outNumber.getBaseTenExponent() - 1 - ); - value *= step; - }; - - while (Math.abs(value) > minMax[1]) - { - outNumber.setBaseTenExponent - ( - outNumber.getBaseTenExponent() + 1 - ); - value /= step; - } - - outNumber.setValue(value); - - return outNumber; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/CultureFeatures.java b/all_code/NumberParser/src_Internal/InternalNumberParser/CultureFeatures.java deleted file mode 100644 index cb37e9b..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/CultureFeatures.java +++ /dev/null @@ -1,7 +0,0 @@ -package InternalNumberParser; - -public enum CultureFeatures -{ - DecimalSeparator, ThousandSeparator, - CurrencySymbol, PercentageSymbol -} \ No newline at end of file diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/ErrorInfoNumber.java b/all_code/NumberParser/src_Internal/InternalNumberParser/ErrorInfoNumber.java deleted file mode 100644 index a06bd9e..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/ErrorInfoNumber.java +++ /dev/null @@ -1,258 +0,0 @@ -package InternalNumberParser; - -import InternalNumberParser.CSharpAdaptation.*; -import NumberParser.*; -import NumberParser.Number; - -@SuppressWarnings("rawtypes") -public class ErrorInfoNumber -{ - public static Object GetNumberXError(Class type, ErrorTypesNumber error) - { - if (type.equals(Number.class)) - { - return new Number(error); - } - else if (type.equals(NumberD.class)) - { - return new NumberD(error); - } - else if (type.equals(NumberO.class)) - { - return new NumberO(error); - } - else if (type.equals(NumberP.class)) - { - return new NumberP(error); - } - - return null; - } - - public static ErrorTypesNumber ApplyPolynomialFitError(Polynomial coefficients, NumberD xValue) - { - ErrorTypesNumber error = ErrorTypesNumber.None; - - if (coefficients == null || xValue == null) error = ErrorTypesNumber.InvalidInput; - if (!coefficients.Error.equals(ErrorTypesNumber.None)) error = coefficients.Error; - if (!xValue.getError().equals(ErrorTypesNumber.None)) error = xValue.getError(); - - return error; - } - - public static ErrorTypesNumber GetPolynomialFitError(NumberD[] xValues, NumberD[] yValues) - { - ErrorTypesNumber error = ErrorTypesNumber.None; - - if - ( - xValues == null || xValues.length == 0 || - yValues == null || yValues.length == 0 - ) - { - error = ErrorTypesNumber.InvalidInput; - } - else if (xValues.length != yValues.length) - { - error = ErrorTypesNumber.InvalidOperation; - } - - return error; - } - - public static ErrorTypesNumber GetFactorialError(NumberD n) - { - ErrorTypesNumber error = - ( - Conversions.ConvertTargetToDouble(n.getValue()) < 0.0 ? - ErrorTypesNumber.InvalidOperation : - GetOperandError(n, NumericTypes.Long) - ); - if (!error.equals(ErrorTypesNumber.None)) return error; - - return - ( - n.greaterOrEqualThan(new NumberD(100000.0)) ? - ErrorTypesNumber.InvalidOperation : ErrorTypesNumber.None - ); - } - - public static ErrorTypesNumber GetPowTruncateError(Number number) - { - return - ( - number == null || !number.getClass().equals(Number.class) ? - ErrorTypesNumber.InvalidInput : ErrorTypesNumber.None - ); - } - - public static ErrorTypesNumber GetOperationError(Object first, Object second, ExistingOperations operation) - { - ErrorTypesNumber error = GetOperandsError(first, second); - if (!error.equals(ErrorTypesNumber.None)) return error; - - NumberX.MainVars mainVars2 = NumberX.GetMainVars(second); - double val2 = Conversions.ConvertTargetToDouble(mainVars2.Value); - - return - ( - ( - operation.equals(ExistingOperations.Division) || - operation.equals(ExistingOperations.Modulo) - ) - && val2 == 0.0 ? - ErrorTypesNumber.InvalidOperation : ErrorTypesNumber.None - ); - } - - public static ErrorTypesNumber GetOperandsError(Object first, Object second) - { - return GetOperandsError(first, second, null); - } - - public static ErrorTypesNumber GetOperandsError(Object first, Object second, NumericTypes target) - { - ErrorTypesNumber error = GetOperandError(first, target); - - return - ( - error.equals(ErrorTypesNumber.None) ? GetOperandError(second, target) : error - ); - } - - public static ErrorTypesNumber GetOperandError(Object input) - { - return GetOperandError(input, null); - } - - public static ErrorTypesNumber GetOperandError(Object input, NumericTypes target) - { - NumberX.MainVars mainVars = NumberX.GetMainVars(input); - - NumberD input2 = - ( - input == null || !Basic.AllNumberClassTypes.contains - ( - input.getClass() - ) - ? null : new NumberD(mainVars.Value, mainVars.BaseTenExponent) - ); - - if (input2 == null || input2.getValue() == null) - { - return ErrorTypesNumber.InvalidInput; - } - if (!input2.getError().equals(ErrorTypesNumber.None)) - { - return input2.getError(); - } - - NumericTypes type = NumericTypesMethods.GetTypeFromObject - ( - input2.getValue() - ); - if (type.equals(NumericTypes.Double) || type.equals(NumericTypes.Float)) - { - ErrorTypesNumber error = GetFloatingTypeError(input2.getValue(), type); - if (!error.equals(ErrorTypesNumber.None)) - { - return ErrorTypesNumber.InvalidInput; - } - } - - return - ( - target != null && !Basic.InputInsideTypeRange(input, target) ? - ErrorTypesNumber.NativeMethodError : ErrorTypesNumber.None - ); - } - - public static ErrorTypesNumber GetConvertToAnyError(Number number, NumericTypes target) - { - if (number == null || !Basic.AllNumericTypes.contains(target)) - { - return ErrorTypesNumber.InvalidInput; - } - - return number.getError(); - } - - public static ErrorTypesNumber GetFloatingTypeError(Object value, NumericTypes type) - { - if (value == null) return ErrorTypesNumber.InvalidInput; - - if (type.equals(NumericTypes.Double)) - { - Double value2 = (Double)value; - if (value2.isInfinite() || value2.isNaN()) - { - return ErrorTypesNumber.InvalidInput; - } - } - else - { - Float value2 = (Float)value; - if (value2.isInfinite() || value2.isNaN()) - { - return ErrorTypesNumber.InvalidInput; - } - } - - return ErrorTypesNumber.None; - } - - public static Class InputTypeIsValidNumericOrNumberX(Object input) - { - return InputTypeIsOK - ( - input, InputType.NumericAndNumberClass - ); - } - - public static NumericTypes InputTypeIsValidNumeric(Object input) - { - return NumericTypesMethods.GetTypeFromClass - ( - InputTypeIsOK - ( - input, InputType.Numeric - ) - ); - } - - private static Class InputTypeIsOK(Object input, InputType inputType) - { - Class type = (input == null ? null : input.getClass()); - if (type == null) return null; - - if (inputType.equals(InputType.NumberClass)) - { - return - ( - Basic.AllNumberClassTypes.contains(type) ? type : null - ); - } - - NumericTypes type2 = NumericTypesMethods.GetTypeFromClass(type); - if (!type2.equals(NumericTypes.None)) - { - if (type2.equals(NumericTypes.Double) || type2.equals(NumericTypes.Float)) - { - if (!GetFloatingTypeError(input, type2).equals(ErrorTypesNumber.None)) - { - return null; - } - } - - return type; - } - - return - ( - inputType.equals(InputType.NumericAndNumberClass) && - Basic.AllNumberClassTypes.contains(type) ? type : null - ); - } - - public enum InputType { Numeric, NumberClass, NumericAndNumberClass } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/ExistingOperations.java b/all_code/NumberParser/src_Internal/InternalNumberParser/ExistingOperations.java deleted file mode 100644 index 948ec30..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/ExistingOperations.java +++ /dev/null @@ -1,9 +0,0 @@ -package InternalNumberParser; - -public enum ExistingOperations -{ - Multiplication, Division, Addition, Subtraction, Greater, GreaterOrEqual, Smaller, - SmallerOrEqual, Modulo, Abs, Acos, Asin, Atan, Atan2, BigMul, Ceiling, Cos, Cosh, - DivRem, Exp, Floor, IEEERemainder, Log, Log10, Max, Min, Pow, Round, Sign, Sin, Sinh, - Sqrt, Tan, Tanh, Truncate -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Common.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Common.java deleted file mode 100644 index cc4adf5..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Common.java +++ /dev/null @@ -1,105 +0,0 @@ -package InternalNumberParser.Math2Internal; - -import InternalNumberParser.*; -import NumberParser.*; - -public class Math2Common -{ - //The differences between the original C# precision (decimal, over 26 decimal digits) and - //the one in the current version (double, 6-8 decimal digits) are much more noticeable in all - //the code associated with the Math2 methods. - //Similarly to what happens in other parts, I have preferred to keep most of the original - //comments, names and structures, even in cases where they aren't strictly required. - //That intention can logically not have a negative impact on the current piece of software - //and this is exactly what happens with all these resources like Power10Double. - public static double[] Power10Double = PopulateRoundPower10Array(); - - public static double[] PopulateRoundPower10Array() - { - return new double[] - { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, - 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, - 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, - 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28 - }; - } - - //This method depends upon the decimal-type native precision/Math.floor and, consequently, - //some extreme cases might be misunderstood. Example: 100000000000000000.00000000000001 - //outputting zero because of being automatically converted into 100000000000000000. - //This method expects the input value to always be positive. - public static int GetHeadingDecimalZeroCount(double d) - { - double d2 = (d > 1.0 ? d - Math.floor(d) : d); - if (d2 == 0) return 0; - - int zeroCount = 0; - while - ( - d2 <= (double)Basic.AllNumberMinMaxPositives.get - ( - NumericTypes.Double - ) - .get(1) * 0.1 - ) - { - d2 *= 10.0; - if (Math.floor(d2 / Power10Double[0] % 10) != 0.0) - { - return zeroCount; - } - zeroCount++; - } - - return zeroCount; - } - - //This method expects the input value to always be positive. - public static int GetIntegerLength(double d) - { - if (d == 0) return 0; - - for (int i = 0; i < Power10Double.length - 1; i++) - { - if (d < Power10Double[i + 1]) return i + 1; - } - - return Power10Double.length; - } - - public static double DecimalPartToInteger(double d2) - { - return DecimalPartToInteger(d2, 0); - } - - public static double DecimalPartToInteger(double d2, int digits) - { - return DecimalPartToInteger(d2, digits, false); - } - - //This method expects the input value to always be positive. - public static double DecimalPartToInteger(double d2, int digits, boolean untilEnd) - { - if (digits + 1 >= Power10Double.length - 1) - { - d2 *= Power10Double[Power10Double.length - 1]; - } - else - { - d2 *= Power10Double[digits + 1]; - double lastDigit = Math.floor(d2 / Power10Double[0] % 10); - while - ( - d2 < Power10Double[Power10Double.length - 3] && - (untilEnd || (lastDigit > 0 && lastDigit <= 5.0)) - ) - { - d2 *= 10; - lastDigit = Math.floor(d2 / Power10Double[0] % 10); - } - } - - return d2; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Existing.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Existing.java deleted file mode 100644 index 5b40389..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Existing.java +++ /dev/null @@ -1,798 +0,0 @@ -package InternalNumberParser.Math2Internal; - -import java.util.ArrayList; -import java.util.Comparator; - -import NumberParser.*; -import NumberParser.Number; -import InternalNumberParser.*; -import InternalNumberParser.CSharpAdaptation.*; -import InternalNumberParser.Operations.*; - -@SuppressWarnings("serial") -public class Math2Existing -{ - public static NumberD PerformOperationOneOperand(NumberD n, ExistingOperations operation) - { - NumberD n2 = AdaptInputsToMathMethod - ( - n, GetTypesOperation(operation), operation - ); - - if (!n2.getError().equals(ErrorTypesNumber.None)) - { - return new NumberD(n2.getError()); - } - - try - { - return ApplyMethod1(n2, operation); - } - catch (Exception e) - { - return new NumberD(ErrorTypesNumber.NativeMethodError); - } - } - - public static NumberD PerformOperationTwoOperands(NumberD n1, NumberD n2, ExistingOperations operation) - { - ArrayList ns = CheckTwoOperands - ( - new ArrayList() - {{ - add(n1); add(n2); - }} - , operation - ); - if (!ns.get(0).getError().equals(ErrorTypesNumber.None)) - { - return ns.get(0); - } - - try - { - return ApplyMethod2 - ( - ns.get(0), ns.get(1), operation - ); - } - catch (Exception e) - { - return new NumberD - ( - ErrorTypesNumber.NativeMethodError - ); - } - } - - static ArrayList CheckTwoOperands(ArrayList ns, ExistingOperations operation) - { - ns = OrderTwoOperands(ns); - - for (int i = 0; i < ns.size(); i++) - { - ArrayList item = null; - - if (i == 0) - { - item = new ArrayList - ( - GetTypesOperation(operation) - ); - } - else - { - item = new ArrayList(); - item.add(ns.get(0).getType()); - } - - ns.set - ( - i, AdaptInputsToMathMethod - ( - ns.get(i), item, operation - ) - ); - - if (!ns.get(i).getError().equals(ErrorTypesNumber.None)) - { - ArrayList tempArray = new ArrayList(); - - tempArray.add - ( - new NumberD(ns.get(i).getError()) - ); - - return tempArray; - } - } - - return ns; - } - - //When checking whether the input types are compatible with what the given Math method - //expects, the order might matter. - //Example: with double and int for a method expecting the same type, the double being analysed - //first provoke the conclusion to always be OK (i.e., int being a different type but implicitly - //convertible to double). On the other hand, if int was analysed first, it would be considered - //invalid because double isn't implicitly convertible to int. - static ArrayList OrderTwoOperands(ArrayList ns) - { - return OrderByDecimalAndRange(ns); - } - - static ArrayList GetTypesOperation(ExistingOperations operation) - { - if - ( - operation == ExistingOperations.Ceiling || - operation == ExistingOperations.Floor || - operation == ExistingOperations.Truncate - ) - { - return new ArrayList() - {{ - add(NumericTypes.Double); - }}; - } - - if (operation == ExistingOperations.Abs || operation == ExistingOperations.Sign) - { - return new ArrayList() - {{ - add(NumericTypes.Double); add(NumericTypes.Float); - add(NumericTypes.Long); add(NumericTypes.Integer); - add(NumericTypes.Short); - }}; - } - - if (operation == ExistingOperations.Max || operation == ExistingOperations.Min) - { - return new ArrayList() - {{ - add(NumericTypes.Double); add(NumericTypes.Float); - add(NumericTypes.Long); add(NumericTypes.Integer); - add(NumericTypes.Short); add(NumericTypes.Byte); - }}; - } - - return new ArrayList() - {{ - add(NumericTypes.Double); add(NumericTypes.Float); - }}; - } - - //The given operation is associated with a Math method with just one argument. - static NumberD ApplyMethod1(NumberD n, ExistingOperations operation) - { - try - { - n.setValue - ( - Conversions.CastDynamicToType(n.getValue(), n.getType()) - ); - - if (operation == ExistingOperations.Abs) - { - n.setValue - ( - Math.abs - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - - return n; - } - else if (operation == ExistingOperations.Ceiling) - { - n.setValue - ( - Math.ceil - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - - return n; - } - else if (operation == ExistingOperations.Floor) - { - n.setValue - ( - Math.floor - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - - return n; - } - else if (operation == ExistingOperations.Truncate) - { - n.setValue - ( - Math2.Truncate(n).getValue() - ); - - return n; - } - else if (operation == ExistingOperations.Sign) - { - n.setValue - ( - Math.signum - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - - return n; - } - - //The operation reaching this point matches the corresponding delegate perfectly. - return ApplyMethod1Delegate(n, operation); - } - catch (Exception e) - { - return new NumberD(ErrorTypesNumber.NativeMethodError); - } - } - - //This method is a Java-adapted version of the original C# ApplyMethod1Delegate, which - //cannot be perfectly replicated because of Java not supporting delegates. - static NumberD ApplyMethod1Delegate(NumberD n, ExistingOperations operation) - { - if (operation == ExistingOperations.Acos) - { - n.setValue - ( - Math.acos - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Asin) - { - n.setValue - ( - Math.asin - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Atan) - { - n.setValue - ( - Math.atan - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Cos) - { - n.setValue - ( - Math.cos - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Cosh) - { - n.setValue - ( - Math.cosh - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Exp) - { - n.setValue - ( - Math.exp - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Log) - { - n.setValue - ( - Math.log - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Log10) - { - n.setValue - ( - Math.log10 - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Sin) - { - n.setValue - ( - Math.sin - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Sinh) - { - n.setValue - ( - Math.sinh - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Sqrt) - { - n.setValue - ( - Math.sqrt - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Sqrt) - { - n.setValue - ( - Math.sqrt - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Tan) - { - n.setValue - ( - Math.tan - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Tanh) - { - n.setValue - ( - Math.tanh - ( - Conversions.ConvertTargetToDouble - ( - n.getValue() - ) - ) - ); - } - - return - ( - ErrorInfoNumber.InputTypeIsValidNumeric - ( - n.getValue() - ) - != null ? n : new NumberD - ( - ErrorTypesNumber.NativeMethodError - ) - ); - } - - static NumberD ApplyMethod2(NumberD n1, NumberD n2, ExistingOperations operation) - { - try - { - n1.setValue - ( - Conversions.CastDynamicToType - ( - n1.getValue(), n1.getType() - ) - ); - - n2.setValue - ( - Conversions.CastDynamicToType - ( - n2.getValue(), n2.getType() - ) - ); - - if (operation == ExistingOperations.Min) - { - n1.setValue - ( - Math.min - ( - Conversions.ConvertTargetToDouble - ( - n1.getValue() - ), - Conversions.ConvertTargetToDouble - ( - n2.getValue() - ) - ) - ); - - return n1; - } - else if (operation == ExistingOperations.Max) - { - n1.setValue - ( - Math.max - ( - Conversions.ConvertTargetToDouble - ( - n1.getValue() - ), - Conversions.ConvertTargetToDouble - ( - n2.getValue() - ) - ) - ); - - return n1; - } - - //The operation reaching this point matches the corresponding delegate perfectly. - return ApplyMethod2Delegate(n1, n2, operation); - } - catch (Exception e) - { - return new NumberD(ErrorTypesNumber.NativeMethodError); - } - } - - //This method is a Java-adapted version of the original C# ApplyMethod1Delegate, which - //cannot be perfectly replicated because of Java not supporting delegates. - static NumberD ApplyMethod2Delegate(NumberD n1, NumberD n2, ExistingOperations operation) - { - if (operation == ExistingOperations.Atan2) - { - n1.setValue - ( - Math.atan2 - ( - Conversions.ConvertTargetToDouble - ( - n1.getValue() - ), - Conversions.ConvertTargetToDouble - ( - n2.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.IEEERemainder) - { - n1.setValue - ( - Math.IEEEremainder - ( - Conversions.ConvertTargetToDouble - ( - n1.getValue() - ), - Conversions.ConvertTargetToDouble - ( - n2.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Log) - { - n1.setValue - ( - Math.log - ( - Conversions.ConvertTargetToDouble - ( - n1.getValue() - ) - ) - / - Math.log - ( - Conversions.ConvertTargetToDouble - ( - n2.getValue() - ) - ) - ); - } - else if (operation == ExistingOperations.Pow) - { - n1.setValue - ( - Math.pow - ( - Conversions.ConvertTargetToDouble - ( - n1.getValue() - ), - Conversions.ConvertTargetToDouble - ( - n2.getValue() - ) - ) - ); - } - - return - ( - ErrorInfoNumber.InputTypeIsValidNumeric - ( - n1.getValue() - ) - != null ? n1 : new NumberD - ( - ErrorTypesNumber.NativeMethodError - ) - ); - } - - //Method adapting the input variable to the requirements of the given Math method. - //If relying on the original type isn't possible, a conversion to double (i.e., biggest-range - //type which is supported by all the Math methods when reaching here) would be performed. - public static NumberD AdaptInputsToMathMethod(NumberD n, ArrayList targets, ExistingOperations operation) - { - if (n == null) return new NumberD(ErrorTypesNumber.InvalidInput); - if (!n.getError().equals(ErrorTypesNumber.None)) return new NumberD(n.getError()); - if (ErrorInfoNumber.InputTypeIsValidNumeric(n.getValue()) == null) - { - return new NumberD(ErrorTypesNumber.InvalidInput); - } - - NumberD n2 = AdaptInputToMathMethod2(new NumberD(n), targets, operation); - if (!n2.getError().equals(ErrorTypesNumber.None)) return n2; - - if (n2.getBaseTenExponent() != 0) - { - n2 = OperationsManaged.PassBaseTenToValue((NumberD)n2); - } - - if (n2.getBaseTenExponent() != 0) - { - if (!n2.getType().equals(NumericTypes.Double)) - { - n2.setValue - ( - Conversions.ConvertToDoubleInternal(n2.getValue()) - ); - n2 = OperationsManaged.PassBaseTenToValue(n2); - } - - if (n2.getBaseTenExponent() != 0) - { - //The value is outside the maximum supported range by the given Math method. - n2 = new NumberD(ErrorTypesNumber.NativeMethodError); - } - } - - return n2; - } - - static NumberD AdaptInputToMathMethod2(NumberD n2, ArrayList targets, ExistingOperations operation) - { - if (!targets.contains(n2.getType())) - { - NumberD n3 = AdaptInputToMathMethodImplicit(n2, targets); - if (n3 != null) return n3; - - if - ( - !n2.getType().equals(NumericTypes.Double) && - !operation.equals(ExistingOperations.DivRem) && - !operation.equals(ExistingOperations.BigMul) - ) - { - //Except DivRem and BigMul, all the Math methods accept double as argument. - n2.setValue - ( - Conversions.ConvertToDoubleInternal(n2.getValue()) - ); - } - else return new NumberD(ErrorTypesNumber.NativeMethodError); - } - - if - ( - !n2.getType().equals(NumericTypes.Double) && - !operation.equals(ExistingOperations.DivRem) && - !operation.equals(ExistingOperations.BigMul) - ) - { - //Except DivRem and BigMul, all the Math methods accept double as argument. - if (!targets.contains(n2.getType())) - { - n2.setValue - ( - Conversions.ConvertToDoubleInternal(n2.getValue()) - ); - } - } - - return n2; - } - - private static NumberD AdaptInputToMathMethodImplicit(NumberD n, ArrayList targets) - { - if (!Basic.AllDecimalTypes.contains(n.getType())) - { - NumericTypes target = LinqNP.FirstOrDefault - ( - OrderByDecimalAndRangeTypes(targets), null - ); - - if (Basic.AllDecimalTypes.contains(target)) - { - //n is an integer and one of the targets is decimal. This means that an implicit - //conversion is possible and, consequently, no further analysis is required to - //conclude that the current input scenario is valid. - return Conversions.ConvertNumberToAny - ( - new Number(n), target - ); - } - } - - return null; - } - - static int CompareTypes(NumericTypes first, NumericTypes second) - { - Boolean val01 = Basic.AllDecimalTypes.contains(first); - Boolean val02 = Basic.AllDecimalTypes.contains(second); - - //.OrderByDescending - //( - // x => Basic.AllDecimalTypes.Contains(x.Type) - //) - //in the original C# code. - int res = val01.compareTo(val02); - if (res != 0) return res; - - Double val11 = - ( - Conversions.ConvertTargetToDouble - ( - Basic.AllNumberMinMaxs.get(first).get(1) - ) - - - Conversions.ConvertTargetToDouble - ( - Basic.AllNumberMinMaxs.get(first).get(0) - ) - ); - - Double val12 = - ( - Conversions.ConvertTargetToDouble - ( - Basic.AllNumberMinMaxs.get(second).get(1) - ) - - - Conversions.ConvertTargetToDouble - ( - Basic.AllNumberMinMaxs.get(second).get(0) - ) - ); - - //.ThenByDescending - //( - // x => Convert.ToDouble(Basic.AllNumberMinMaxs[x.Type][1]) - - // Convert.ToDouble(Basic.AllNumberMinMaxs[x.Type][0]) - //) - //in the original C# code. - return val11.compareTo(val12); - } - - static ArrayList OrderByDecimalAndRange(ArrayList ns) - { - return LinqNP.OrderByDescending - ( - ns, new Comparator() - { - public int compare(NumberD first, NumberD second) - { - return CompareTypes - ( - first.getType(), second.getType() - ); - } - } - ); - } - - static ArrayList OrderByDecimalAndRangeTypes(ArrayList types) - { - return LinqNP.OrderByDescending - ( - types, new Comparator() - { - public int compare(NumericTypes first, NumericTypes second) - { - return CompareTypes(first, second); - } - } - ); - } -} \ No newline at end of file diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Other.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Other.java deleted file mode 100644 index e704347..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Other.java +++ /dev/null @@ -1,41 +0,0 @@ -package InternalNumberParser.Math2Internal; - -import NumberParser.*; -import InternalNumberParser.*; -import InternalNumberParser.Operations.*; - -public class Math2Other -{ - public static NumberD FactorialInternal(NumberD n) - { - ErrorTypesNumber error = ErrorInfoNumber.GetFactorialError(n); - if (!error.equals(ErrorTypesNumber.None)) return new NumberD(error); - if (Conversions.ConvertTargetToDouble(n.getValue()) <= 1.0) - { - return new NumberD(Conversions.CastDynamicToType(1, n.getType())); - } - - NumericTypes type = n.getType(); - if (!type.equals(NumericTypes.Long) && !type.equals(NumericTypes.Integer)) - { - n.setValue((long)n.getValue()); - } - n = OperationsManaged.PassBaseTenToValue(n); - - //At this point, output.BaseTenExponent has to be zero. - NumberD output = new NumberD(1, n.getType()); - double i = 2.0; - double val = Conversions.ConvertTargetToDouble(n.getValue()); - - while (i <= val) - { - output = OperationsManaged.MultiplyInternal - ( - output, new NumberD(i) - ); - i++; - } - - return output; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2PowSqrt.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2PowSqrt.java deleted file mode 100644 index 5a732ee..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2PowSqrt.java +++ /dev/null @@ -1,142 +0,0 @@ -package InternalNumberParser.Math2Internal; - -import NumberParser.*; -import NumberParser.Number; -import InternalNumberParser.*; -import InternalNumberParser.Operations.*; - -//This class contains a very limited version of the code in the original C# version dealing with -//PowDecimal/SqrtDecimal. -//Note that the custom parts (Newton-Raphson + my improvements) don't make too much sense in this -//specific context. My intention when developing all that was to allow the very high precision -//(accurately dealing with up to 27-28 decimal positions!) of the .NET decimal type to be fully -//maximised, as opposed to what the in-built Pow/Sqrt methods do (i.e., accounting for the much less -//precise double type, accurately dealing with up to 7-9 decimal positions). As far as this Java -//implementation has to forcibly rely on the double type, the point of that custom approach was -//pretty much lost. -//In any case, I did try to adapt that original code to the double/Java peculiarities mainly to be -//consistent with my intention of creating an as-similar-to-C#-as-possible Java version; but soon I -//realised about the low applicability of that original approach to these new conditions. Having fully -//redeveloped my custom approach just to deliver a similar precision to what the in-built methods already -//do wouldn't have made too much sense. That's why I decided to implement the current version which is -//just a simple wrapper allowing to use Math.pow/Math.sqrt with Number variables. -public class Math2PowSqrt -{ - public static Number PowSqrtInternal(Number number, double exponent) - { - return PowSqrtInternal(number, exponent, true); - } - - public static Number PowSqrtInternal(Number number, double exponent, boolean showUser) - { - ErrorTypesNumber error = ErrorInfoNumber.GetPowTruncateError(number); - if (!error.equals(ErrorTypesNumber.None)) return new Number(error); - - boolean isSqrt = (exponent == 0.5); - boolean expIsInteger = (exponent == Math.floor(exponent)); - - Number tempVar = PowSqrtPreCheck(number, exponent, expIsInteger); - if (tempVar != null) return tempVar; - - Number outNumber = OperationsManaged.PassBaseTenToValue(number); - - //The BaseTenExponent is calculated independently in order to avoid operations with too big values. - //Note that this BaseTenExponent represents all the additional information on top of the maximum - //double range. During the calculations, the outNumber variable will be normalised and, consequently, - //a new BaseTenExponent will be used. - int baseTenExp = outNumber.getBaseTenExponent(); - outNumber.setBaseTenExponent(0); - - //Better simplifying the intermediate calculations as much as possible by ignoring all the signs. - double sign = - ( - exponent % 2 == 0 ? 1.0 : Math.signum(outNumber.getValue()) - ); - outNumber.setValue(Math.abs(outNumber.getValue())); - - double sign2 = Math.signum(exponent); - exponent = Math.abs(exponent); - - if (isSqrt) - { - outNumber = OperationsManaged.MultiplyInternal - ( - new Number(sign), new Number(Math.sqrt(outNumber.getValue())) - ); - } - else - { - outNumber = new Number(Math.pow(outNumber.getValue(), exponent)); - - outNumber.setValue(sign * outNumber.getValue()); - - if (sign2 == -1) - { - outNumber = OperationsManaged.DivideInternal - ( - new Number(1.0), outNumber - ); - } - } - - if (baseTenExp != 0) - { - outNumber = OperationsManaged.MultiplyInternal - ( - outNumber, RaiseBaseTenToExponent(baseTenExp, exponent) - ); - } - - return OperationsManaged.PassBaseTenToValue(outNumber, showUser); - } - - static Number PowSqrtPreCheck(Number number, double exponent, boolean expIsInteger) - { - if (number.getValue() < 0.0 && !expIsInteger) - { - return new Number(ErrorTypesNumber.InvalidOperation); - } - if - ( - number.equals(new Number(1.0)) || - number.equals(new Number(0.0)) || exponent == 1.0 - ) - { return new Number(number); } - - if (exponent == 0.0) return new Number(1.0); - if (number.equals(new Number(-1.0))) - { - return new Number(exponent % 2 == 0 ? 1.0 : -1.0); - } - - return null; - } - - static Number RaiseBaseTenToExponent(int existingBaseTen, double exponent) - { - double tempBaseTen = existingBaseTen * exponent; - if - ( - (existingBaseTen < 0 && tempBaseTen < Integer.MIN_VALUE - existingBaseTen) || - (existingBaseTen > 0 && tempBaseTen > Integer.MAX_VALUE - existingBaseTen) - ) - { return new Number(ErrorTypesNumber.NumericOverflow); } - - Number outNumber = new Number(1.0, (int)tempBaseTen); - return - ( - outNumber.getBaseTenExponent() == tempBaseTen ? - outNumber : OperationsManaged.MultiplyInternal - ( - outNumber, new Number - ( - Math.pow - ( - 10.0, tempBaseTen - - outNumber.getBaseTenExponent() - ) - ) - ) - ); - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Regression.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Regression.java deleted file mode 100644 index 401de78..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2Regression.java +++ /dev/null @@ -1,253 +0,0 @@ -package InternalNumberParser.Math2Internal; - -import NumberParser.*; -import NumberParser.Number; -import InternalNumberParser.*; -import InternalNumberParser.Operations.*; - -public class Math2Regression -{ - public static NumberD ApplyPolynomialFitInternal(Polynomial coefficients, NumberD xValue) - { - ErrorTypesNumber error = ErrorInfoNumber.ApplyPolynomialFitError - ( - coefficients, xValue - ); - if (!error.equals(ErrorTypesNumber.None)) return new NumberD(error); - - if (!coefficients.A.getType().equals(xValue.getType())) - { - xValue = Conversions.ConvertNumberToAny - ( - new Number(xValue), coefficients.A.getType() - ); - } - - //coefficients.A + coefficients.B * xValue + coefficients.C * xValue * xValue; - return OperationsManaged.AddInternal - ( - coefficients.A, OperationsManaged.AddInternal - ( - OperationsManaged.MultiplyInternal(coefficients.B, xValue), - OperationsManaged.MultiplyInternal - ( - coefficients.C, OperationsManaged.MultiplyInternal - ( - xValue, xValue - ) - ) - ) - ); - } - - public static Polynomial GetPolynomialFitInternal(NumberD[] xValues, NumberD[] yValues) - { - ErrorTypesNumber error = ErrorInfoNumber.GetPolynomialFitError(xValues, yValues); - if (!error.equals(ErrorTypesNumber.None)) return new Polynomial(error); - - NumericTypes type = xValues[0].getType(); - if (!Basic.AllDecimalTypes.contains(type)) - { - //An integer type would provoke the subsequent calculations to fail. - type = NumericTypes.Double; - } - xValues = SyncType(xValues, type); - yValues = SyncType(yValues, type); - - //Getting the coefficients matrix generated after calculating least squares. - GetGaussJordanCoeffs(xValues, yValues, type); - - for (int i = 0; i < 3; i++) - { - for (int i2 = 0; i2 < 3; i2++) - { - if (i != i2) - { - //factor = - //( - // GaussJordan.a[i, i] == 0 ? 0 : - // -1 * GaussJordan.a[i2, i] / GaussJordan.a[i, i] - //); - - NumberD factor = - ( - GaussJordan.a[i][i] == new NumberD(type) ? new NumberD(type) : - OperationsManaged.MultiplyInternal - ( - new NumberD(Basic.GetNumberSpecificType(-1, type)), - OperationsManaged.DivideInternal - ( - GaussJordan.a[i2][i], GaussJordan.a[i][i] - ) - ) - ); - - for (int i3 = 0; i3 < 3; i3++) - { - //GaussJordan.a[i2, i3] = factor * GaussJordan.a[i, i3] + GaussJordan.a[i2, i3]; - GaussJordan.a[i2][i3] = OperationsManaged.AddInternal - ( - OperationsManaged.MultiplyInternal - ( - factor, GaussJordan.a[i][i3] - ), - GaussJordan.a[i2][i3] - ); - } - - //GaussJordan.b[i2] = factor * GaussJordan.b[i] + GaussJordan.b[i2]; - GaussJordan.b[i2] = OperationsManaged.AddInternal - ( - OperationsManaged.MultiplyInternal - ( - factor, GaussJordan.b[i] - ), - GaussJordan.b[i2] - ); - } - } - } - - return new Polynomial - ( - CalculatePolynomialCoefficient(0, type), - CalculatePolynomialCoefficient(1, type), - CalculatePolynomialCoefficient(2, type) - ); - } - - static NumberD[] SyncType(NumberD[] array, NumericTypes type) - { - for (int i = 0; i < array.length; i++) - { - if (!array[i].getType().equals(type)) - { - array[i] = Conversions.ConvertNumberToAny - ( - new Number(array[i]), type - ); - } - } - - return array; - } - - static NumberD CalculatePolynomialCoefficient(int i, NumericTypes type) - { - return - ( - GaussJordan.a[i][i] == new NumberD(type) ? - new NumberD(type) : OperationsManaged.DivideInternal - ( - GaussJordan.b[i], GaussJordan.a[i][i] - ) - ); - } - - static void GetGaussJordanCoeffs - ( - NumberD[] xValues, NumberD[] yValues, NumericTypes type - ) - { - LeastSquares.StartLeastSquares(type); - - for (int i = 0; i < xValues.length; i++) - { - NumberD curX2 = new NumberD - ( - OperationsManaged.MultiplyInternal - ( - xValues[i], xValues[i] - ) - ); - - LeastSquares.sumX1 = OperationsManaged.AddInternal - ( - LeastSquares.sumX1, xValues[i] - ); - LeastSquares.sumX2 = OperationsManaged.AddInternal - ( - LeastSquares.sumX2, curX2 - ); - LeastSquares.sumX12 = OperationsManaged.AddInternal - ( - LeastSquares.sumX12, OperationsManaged.MultiplyInternal - ( - xValues[i], curX2 - ) - ); - LeastSquares.sumX1Y = OperationsManaged.AddInternal - ( - LeastSquares.sumX1Y, OperationsManaged.MultiplyInternal - ( - xValues[i], yValues[i] - ) - ); - LeastSquares.sumX22 = OperationsManaged.AddInternal - ( - LeastSquares.sumX22, OperationsManaged.MultiplyInternal - ( - curX2, curX2 - ) - ); - LeastSquares.sumX2Y = OperationsManaged.AddInternal - ( - LeastSquares.sumX2Y, OperationsManaged.MultiplyInternal - ( - curX2, yValues[i] - ) - ); - LeastSquares.sumY = OperationsManaged.AddInternal - ( - LeastSquares.sumY, yValues[i] - ); - } - - //a/b arrays emulating the matrix storing the least square outputs, as defined by: - // a[0, 0] a[0, 1] a[0, 2] | b[0] - // a[1, 0] a[1, 1] a[1, 2] | b[1] - // a[2, 0] a[2, 1] a[2, 2] | b[2] - GaussJordan.StartGaussJordan(); - GaussJordan.a[0][0] = new NumberD(xValues.length); - GaussJordan.a[0][1] = LeastSquares.sumX1; - GaussJordan.a[0][2] = LeastSquares.sumX2; - GaussJordan.a[1][0] = LeastSquares.sumX1; - GaussJordan.a[1][1] = LeastSquares.sumX2; - GaussJordan.a[1][2] = LeastSquares.sumX12; - GaussJordan.a[2][0] = LeastSquares.sumX2; - GaussJordan.a[2][1] = LeastSquares.sumX12; - GaussJordan.a[2][2] = LeastSquares.sumX22; - - GaussJordan.b[0] = LeastSquares.sumY; - GaussJordan.b[1] = LeastSquares.sumX1Y; - GaussJordan.b[2] = LeastSquares.sumX2Y; - } - - static class GaussJordan - { - public static NumberD[][] a; - public static NumberD[] b; - - public static void StartGaussJordan() - { - a = new NumberD[3][3]; - b = new NumberD[3]; - } - } - - static class LeastSquares - { - public static NumberD sumX1, sumX2, sumX12, sumX1Y, sumX22, sumX2Y, sumY; - - public static void StartLeastSquares(NumericTypes type) - { - sumX1 = new NumberD(type); - sumX2 = new NumberD(type); - sumX12 = new NumberD(type); - sumX1Y = new NumberD(type); - sumX22 = new NumberD(type); - sumX2Y = new NumberD(type); - sumY = new NumberD(type); - } - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2RoundTruncate.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2RoundTruncate.java deleted file mode 100644 index 719d485..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Math2Internal/Math2RoundTruncate.java +++ /dev/null @@ -1,237 +0,0 @@ -package InternalNumberParser.Math2Internal; - -import NumberParser.*; -import NumberParser.Number; -import InternalNumberParser.*; - -public class Math2RoundTruncate -{ - public static Number RoundExactInternal(Number number, int digits, RoundType type, RoundSeparator separator) - { - ErrorTypesNumber error = ErrorInfoNumber.GetPowTruncateError(number); - if (!error.equals(ErrorTypesNumber.None)) return new Number(error); - - if (digits <= 0) digits = 0; - if (digits > Math2Common.Power10Double.length - 1) - { - digits = Math2Common.Power10Double.length - 1; - } - - Number outNumber = new Number(number); - - outNumber.setValue - ( - Math.signum(number.getValue()) * RoundInternal - ( - Math.abs(outNumber.getValue()), digits, type, separator - ) - ); - - return outNumber; - } - - private static double RoundInternal(double d, int digits, RoundType type, RoundSeparator separator) - { - return - ( - digits == 0 || separator == RoundSeparator.BeforeDecimalSeparator ? - RoundInternalBefore(d, digits, type) : RoundInternalAfter(d, digits, type) - ); - } - - private static double RoundInternalBefore(double d, int digits, RoundType type) - { - if (digits == 0) return PerformRound(d, 0, type, Math.floor(d)); - - int length = Math2Common.GetIntegerLength(d); - - return - ( - digits > length ? d : RoundExactInternal - ( - d, length - digits, type - ) - ); - } - - private static double RoundInternalAfterNoZeroes(double d, double d2, int digits, RoundType type) - { - d2 = Math2Common.DecimalPartToInteger(d2, digits); - int length2 = Math2Common.GetIntegerLength(d2); - - return - ( - digits >= length2 ? d : Math.floor(d) + - ( - RoundExactInternal - ( - d2, length2 - digits, type - ) - / Math2Common.Power10Double[length2] - ) - ); - } - - private static double RoundInternalAfterZeroes(double d, int digits, RoundType type, double d2, int zeroCount) - { - if (digits < zeroCount) - { - //Cases like 0.001 with 1 digit or 0.0001 with 2 digits can reach this point. - //On the other hand, something like 0.001 with 2 digits requires further analysis. - return Math.floor(d) + - ( - !type.equals(RoundType.AlwaysAwayFromZero) ? 0.0 : - 1.0 / Math2Common.Power10Double[digits] - ); - } - - //d3 represent the double part after all the heading zeroes. - double d3 = d2 * Math2Common.Power10Double[zeroCount]; - d3 = Math2Common.DecimalPartToInteger(d3 - Math.floor(d3), 0, true); - int length3 = Math2Common.GetIntegerLength(d3); - - double headingBit = 0; - digits -= zeroCount; - if (digits == 0) - { - //In a situation like 0.005 with 2 digits, the number to be analysed would be - //05 what cannot be (i.e., treated as 5, something different). That's why, in - //these cases, adding a heading number is required. - headingBit = 2; //2 avoids the ...ToEven types to be misinterpreted. - d3 = headingBit * Math2Common.Power10Double[length3] + d3; - digits = 0; - } - - double output = - ( - RoundExactInternal(d3, length3 - digits, type) - / Math2Common.Power10Double[length3] - ) - - headingBit; - - return Math.floor(d) + - ( - output == 0.0 ? 0.0 : - output / Math2Common.Power10Double[zeroCount] - ); - } - - private static double RoundInternalAfter(double d, int digits, RoundType type) - { - double d2 = d - Math.floor(d); - int zeroCount = Math2Common.GetHeadingDecimalZeroCount(d2); - - return - ( - zeroCount == 0 ? RoundInternalAfterNoZeroes(d, d2, digits, type) : - RoundInternalAfterZeroes(d, digits, type, d2, zeroCount) - ); - } - - private static double RoundExactInternal(double d, int remDigits, RoundType type) - { - double rounded = PerformRound - ( - d, remDigits, type, - Math.floor(d / Math2Common.Power10Double[remDigits]) - ); - - double rounded2 = rounded * Math2Common.Power10Double[remDigits]; - return - ( - rounded2 > rounded ? rounded2 : - d //A numeric overflow occurred. - ); - } - - private static double PerformRound(double d, int remDigits, RoundType type, double rounded) - { - if (type == RoundType.AlwaysToZero || type == RoundType.AlwaysAwayFromZero) - { - return rounded + - ( - type == RoundType.AlwaysAwayFromZero ? 1.0 : 0.0 - ); - } - else - { - int lastDigit = (int)(d / Math2Common.Power10Double[remDigits] % 10.0); - - if (type == RoundType.AlwaysToEven) - { - if (lastDigit % 2 != 0) rounded += 1.0; - } - else - { - int greaterEqual = MidPointGreaterEqual(d, remDigits, rounded); - - if (greaterEqual == 1) rounded += 1.0; - else if (greaterEqual == 0) - { - if (type == RoundType.MidpointAwayFromZero || (type == RoundType.MidpointToEven && lastDigit % 2 != 0)) - { - rounded += 1.0; - } - } - } - } - - return rounded; - } - - private static int MidPointGreaterEqual(double d, int remDigits, double rounded) - { - return - ( - remDigits > 0 ? - //There are some additional digits after the last rounded one. It can be before or after. - //Example: 12345.6789 being rounded to 12000 or to 12345.68. - MidPointGreaterEqualRem(d, remDigits, rounded) : - //No additional digits after the last rounded one and the double digits have to be considered. - //Only before is relevant here. Example: 12345.6789 rounded to 12345 and considering .6789. - MidPointGreaterEqualNoRem(d, rounded) - ); - } - - private static int MidPointGreaterEqualNoRem(double d, double rounded) - { - double d2 = d - rounded; - d2 = Math2Common.DecimalPartToInteger(d2 - Math.floor(d2)); - int length2 = Math2Common.GetIntegerLength(d2); - if (length2 < 1) return 0; - - int nextDigit = (int)(d2 / Math2Common.Power10Double[length2 - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - while (Math.floor(d2) != d2 && d2 < Math2Common.Power10Double[Math2Common.Power10Double.length - 1]) - { - d2 *= 10; - length2++; - } - - int count = length2 - 1; - while (count > 0) - { - count--; - if ((int)(d2 / Math2Common.Power10Double[count] % 10) != 0) - { - //Just one digit different than zero is enough to conclude that is greater. - return 1; - } - } - - return 0; - } - - private static int MidPointGreaterEqualRem(double d, int remDigits, double rounded) - { - int nextDigit = (int)(d / Math2Common.Power10Double[remDigits - 1] % 10); - if (nextDigit != 5) return (nextDigit < 5 ? -1 : 1); - - double middle = nextDigit * Math.floor(Math2Common.Power10Double[remDigits - 1]); - return - ( - d - rounded * Math.floor(Math2Common.Power10Double[remDigits]) == middle ? 0 : 1 - ); - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/NumberOInternal.java b/all_code/NumberParser/src_Internal/InternalNumberParser/NumberOInternal.java deleted file mode 100644 index 93306a1..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/NumberOInternal.java +++ /dev/null @@ -1,104 +0,0 @@ -package InternalNumberParser; - -import java.util.ArrayList; - -import NumberParser.*; - -@SuppressWarnings("serial") -public class NumberOInternal -{ - public static ArrayList PopulateOthers(double value, int baseTenExponent, ArrayList types) - { - ArrayList outList = new ArrayList(); - if (types == null) return outList; - - for (NumericTypes type: types) - { - outList.add - ( - new NumberD(value, baseTenExponent, type) - ); - } - - return outList; - } - - public static ArrayList CheckOtherTypes(ArrayList types) - { - ArrayList output = new ArrayList(); - if (types == null || types.size() == 0) - { - return output; - } - - for (NumericTypes type: types) - { - if (!type.equals(NumericTypes.None) && !type.equals(NumericTypes.Double)) - { - output.add(type); - } - } - - return output; - } - - public static ArrayList GetAssociatedTypes(OtherTypes otherType) - { - ArrayList types = null; - - if (otherType.equals(OtherTypes.AllTypes)) - { - types = new ArrayList(Basic.AllNumericTypes); - } - else if (otherType.equals(OtherTypes.MostCommonTypes)) - { - types = new ArrayList() - {{ - add(NumericTypes.Double); - add(NumericTypes.Long); - add(NumericTypes.Integer); - }}; - } - else if (otherType.equals(OtherTypes.DecimalTypes)) - { - types = new ArrayList() - {{ - add(NumericTypes.Double); - add(NumericTypes.Float); - }}; - } - else if (otherType.equals(OtherTypes.IntegerTypes)) - { - types = new ArrayList() - {{ - add(NumericTypes.Long); - add(NumericTypes.Integer); - add(NumericTypes.Short); - add(NumericTypes.Byte); - add(NumericTypes.Character); - }}; - } - else if (otherType.equals(OtherTypes.BigTypes)) - { - types = new ArrayList() - {{ - add(NumericTypes.Double); - add(NumericTypes.Float); - add(NumericTypes.Long); - add(NumericTypes.Integer); - }}; - } - else if (otherType.equals(OtherTypes.SmallTypes)) - { - types = new ArrayList() - {{ - add(NumericTypes.Short); - add(NumericTypes.Byte); - add(NumericTypes.Character); - }}; - } - else types = new ArrayList(); - - return types; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/NumberPInternal.java b/all_code/NumberParser/src_Internal/InternalNumberParser/NumberPInternal.java deleted file mode 100644 index 066c619..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/NumberPInternal.java +++ /dev/null @@ -1,590 +0,0 @@ -package InternalNumberParser; - -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Locale; - -import InternalNumberParser.CSharpAdaptation.*; -import InternalNumberParser.Operations.*; -import NumberParser.*; -import NumberParser.Number; - -@SuppressWarnings("serial") -public class NumberPInternal -{ - public static NumberD StartParse(ParseInfo info) - { - ParseInfo info2 = new ParseInfo(info); - info2.OriginalString = RemoveValidRedundant - ( - info2.OriginalString, - info2.Config.getCulture() - ); - - //The blank spaces are supported as thousands separators in any case (i.e., independently upon the ParseType - //value). But they have to be replace with standard separators to avoid parsing problems (the native parse - //methods don't support them). - if (info2.OriginalString.contains(" ")) - { - ArrayList thousands = GetCultureFeature - ( - CultureFeatures.ThousandSeparator, - info2.Config.getCulture() - ); - - if (thousands.size() > 0) - { - info2.OriginalString = CSharpOtherNP.StringJoin - ( - thousands.get(0), CSharpOtherNP.SplitTryCatch - ( - info2.OriginalString, " " - ) - ); - } - } - - if - ( - info2.Config.getParseType().equals(ParseTypes.ParseThousandsStrict) || - info2.Config.getParseType().equals(ParseTypes.ParseOnlyTargetAndThousandsStrict) - ) - { - //Method determining whether the thousands separators are valid or not. - info2 = AnalyseThousands(info2); - if (!info2.Number.getError().equals(ErrorTypesNumber.None)) - { - return new NumberD(info2.Number.getError()); - } - } - - return - ( - info2.Config.getTarget().equals(NumericTypes.Double) ? - new NumberD - ( - ParseDoubleAndBeyond - ( - info2.OriginalString, - info2.Config.getCulture() - ) - ) - : ParseToSpecificType - ( - info2.OriginalString, info2.Config - ) - ); - } - - //Removing all the symbols associated with the current culture which, although technically valid, might - //provoke some problems under certain parsing conditions. - static String RemoveValidRedundant(String input, Locale culture) - { - CultureFeatures[] features = new CultureFeatures[] - { - CultureFeatures.CurrencySymbol, CultureFeatures.PercentageSymbol - }; - - String output = input; - - for (CultureFeatures feature: features) - { - for (String item : GetCultureFeature(feature, culture)) - { - output = output.replace(item, ""); - } - } - - return output; - } - - static ParseInfo AnalyseThousands(ParseInfo info) - { - ParseInfo error = new ParseInfo(info, ErrorTypesNumber.ParseError); - ArrayList separators = GetCultureFeature - ( - CultureFeatures.ThousandSeparator, info.Config.getCulture() - ); - if (separators.size() == 0) return error; - - //Removing the decimal part (+ making sure that it doesn't include any thousands separator) if existing. - String string2 = RemoveDecimalsForThousands - ( - info.OriginalString, info.Config.getCulture(), separators - ); - - ArrayList groups = CSharpOtherNP.SplitTryCatchMulti - ( - string2, separators - ); - if (groups.size() < 2) return error; - - int count = 0; - while (count < 3) - { - count++; - if (ThousandsAreOK(groups, count)) - { - return info; - } - } - - return error; - } - - static String RemoveDecimalsForThousands - ( - String input, Locale culture, ArrayList separators - ) - { - ArrayList decimals = GetCultureFeature - ( - CultureFeatures.DecimalSeparator, culture - ); - ArrayList tempVar = CSharpOtherNP.SplitTryCatchMulti - ( - input, decimals - ); - if (tempVar.size() != 2) - { - return - ( - tempVar.size() > 2 ? "" : input - ); - } - - if - ( - LinqNP.FirstOrDefault - ( - CSharpOtherNP.StringToCharacters(input), - ( - x -> x == ' ' || separators.contains - ( - x.toString() - ) - ) - , '\0' - ) - != '\0' - ) - { return ""; } - - TryParseOutputNP tempVar2 = TryParseMethodsNP.Integer - ( - tempVar.get(1), culture - ); - - return - ( - !tempVar2.IsOK ? "" : tempVar.get(0) - ); - } - - static boolean ThousandsAreOK(ArrayList groups, int type) - { - int target = 3; //Standard -> groups of 3. - if (type == 3) - { - //Chinese -> groups of 4. - target = 4; - } - - //The last group (i = 0) doesn't need to be analysed (undefined size for all the types). - for (int i = groups.size() - 1; i > 0; i--) - { - if (target != 0 && groups.get(i).length() != target) - { - return false; - } - - if (type == 2) - { - //Indian -> first group of 3; the remaining groups of 2. - target = 2; - } - } - - return true; - } - - static NumberD ParseToSpecificType(String input, ParseConfig config) - { - NumericTypes type = config.getTarget(); - - boolean precheckIt = false; - double val0 = 0.0; - if (!type.equals(NumericTypes.None)) - { - TryParseOutputNP tempVar = TryParseMethodsNP.Double - ( - input, config.getCulture() - ); - - if (tempVar.IsOK) - { - if (type.equals(NumericTypes.Double)) - { - return new NumberD(tempVar.DoubleVal); - } - - precheckIt = true; - val0 = tempVar.DoubleVal; - } - } - - if (precheckIt) - { - if - ( - val0 >= Conversions.ConvertTargetToDouble - ( - Basic.AllNumberMinMaxs.get(type).get(0) - ) - ) - { - if - ( - val0 <= Conversions.ConvertTargetToDouble - ( - Basic.AllNumberMinMaxs.get(type).get(1) - ) - ) - { return new NumberD(val0, type); } - } - } - - return - ( - config.getParseType().equals(ParseTypes.ParseAll) || - config.getParseType().equals(ParseTypes.ParseThousandsStrict) ? - //The input string cannot be directly parsed to the target type. - //Under these conditions, there is a second chance: relying on ParseAnyMain which parses any string - //fitting the Number range (+ the more permissive parsing rules of this library) and adapts its output - //to the target type. - ParseAnyMain(input, config) : - new NumberD(ErrorTypesNumber.NativeMethodError) - ); - } - - static boolean InputIsCultureFeature - ( - String input, CultureFeatures feature, Locale culture - ) - { - for (String item: GetCultureFeature(feature, culture)) - { - if (item.equals(input)) return true; - } - - return false; - } - - static ArrayList GetDecimalGroupSeparators(NumberFormat numberFormat, boolean isGroup) - { - DecimalFormatSymbols tempVar = - ( - (DecimalFormat)numberFormat - ) - .getDecimalFormatSymbols(); - - ArrayList output = new ArrayList() - {{ - add - ( - new Character - ( - isGroup ? tempVar.getGroupingSeparator() : - tempVar.getDecimalSeparator() - ) - .toString() - ); - }}; - - if (isGroup) return output; - - String tempVar2 = new Character - ( - tempVar.getMonetaryDecimalSeparator() - ) - .toString(); - - if (output.get(0) != tempVar2) - { - output.add(tempVar2); - } - - return output; - } - - static ArrayList GetCultureFeature(CultureFeatures feature, Locale culture) - { - if (culture == null) return new ArrayList(); - - NumberFormat numberFormat = NumberFormat.getInstance(culture); - - if (feature.equals(CultureFeatures.DecimalSeparator)) - { - return GetDecimalGroupSeparators(numberFormat, false); - //All the decimal (or thousands) separators associated with a given culture are (almost?) always - //identical. In any case, associating a given character to certain subtype (number/currency/percentage) - //would go against the overall attitude of this library (i.e., parsing as restrictionless as possible). - //That's why all of the separators are treated indistinctively. - } - else if (feature.equals(CultureFeatures.ThousandSeparator)) - { - return GetDecimalGroupSeparators(numberFormat, true); - } - else if (feature.equals(CultureFeatures.CurrencySymbol)) - { - return new ArrayList() - {{ - add - ( - numberFormat.getCurrency().getSymbol() - ); - }}; - } - else if (feature.equals(CultureFeatures.PercentageSymbol)) - { - ArrayList output = new ArrayList(); - output.add("%"); - output.add("‰"); - - return output; - } - - return new ArrayList(); - } - - static NumberD ParseAnyMain(String input, ParseConfig config) - { - return Conversions.ConvertNumberToAny - ( - ParseDoubleAndBeyond(input, config.getCulture()), config.getTarget() - ); - } - - static Number ParseDoubleAndBeyond(String input, Locale culture) - { - TryParseOutputNP tempVar = TryParseMethodsNP.Double(input, culture); - - return - ( - tempVar.IsOK && tempVar.DoubleVal != 0.0 ? - Conversions.ConvertDoubleToNumber(tempVar.DoubleVal) : - ParseBeyondDouble(input, culture) - ); - } - - private static Number ParseBeyondDouble(String input, Locale culture) - { - String stringToParse = input.trim().toLowerCase(); - - //The numeric-parsing .NET format is expected. That is: only integer exponents after the letter "e", what - //has to be understood as before-e * 10^after-e. - if (stringToParse.contains("e")) - { - double[] tempVals = ExponentialPartsAnalysis - ( - stringToParse, culture - ); - - if (tempVals != null) - { - return (Number)OperationsOther.VaryBaseTenExponent - ( - Conversions.ConvertDoubleToNumber(tempVals[0]), (int)tempVals[1] - ); - } - } - else - { - if (stringToParse.length() < 300) - { - TryParseOutputNP tempVar = TryParseMethodsNP.Double - ( - stringToParse, culture - ); - - if (tempVar.IsOK) - { - return Conversions.ConvertDoubleToNumber - ( - tempVar.DoubleVal - ); - } - } - else - { - TryParseOutputNP tempVar = TryParseMethodsNP.Double - ( - stringToParse.substring(0, 299), culture - ); - - if (tempVar.IsOK) - { - String remString = stringToParse.substring(299); - - boolean isOK = LinqNP.FirstOrDefault - ( - CSharpOtherNP.StringToCharacters(remString), - x -> !Character.isDigit(x) && !InputIsCultureFeature - ( - x.toString(), CultureFeatures.ThousandSeparator, culture - ) - , '\0' - - ) - != '\0'; - - if (isOK) - { - //Finding a decimal separator here is considered an error because it wouldn't - //be too logical (300 digits before the decimal separator!). Mainly by bearing - //in mind the exponential alternative above. - return new Number(ErrorTypesNumber.InvalidInput); - } - - int beyondCount = GetBeyondDoubleCharacterCount - ( - stringToParse.substring(299), culture - ); - - if (beyondCount <= 0) - { - return new Number - ( - beyondCount == 0 ? - ErrorTypesNumber.InvalidInput : - ErrorTypesNumber.NumericOverflow - ); - } - - //Accounting for the differences 0.001/1000 -> 10^-3/10^3. - int sign = - ( - Math.abs(tempVar.DoubleVal) < 1.0 ? -1 : 1 - ); - - if (tempVar.DoubleVal == 0.0 && sign == -1) - { - //This code accounts for situations like 0.00000[...]00001 where, - //for the aforementioned double.TryParse, tempVar.DoubleVal is zero. - boolean found = false; - int length2 = - ( - remString.length() > 299 ? - 299 : remString.length() - ); - - char[] remString2 = remString.toCharArray(); - for (int i = 0; i < remString2.length; i++) - { - if - ( - remString2[i] != '0' && !InputIsCultureFeature - ( - ((Character)remString2[i]).toString(), - CultureFeatures.ThousandSeparator, culture - ) - ) - { - - //The default interpretation is initial_part*10^remString.Length (up to the maximum length natively supported by double). - //For example, 0.0000012345[...]4565879561424 is correctly understood as 0.0000012345*10^length-after-[...]. In this specific - //situation (i.e., initial_part understood as zero), some digits after [...] have to also be considered to form initial_part. - //Thus, tempVar.DoubleVal is being redefined as all the digits (up to the maximum length natively supported by double) after the - //first non-zero one; and beyondCount (i.e., the associated 10-base exponent) such that it also includes all the digits since the start. - found = true; - tempVar.DoubleVal = TryParseMethodsNP.Double - ( - CSharpOtherNP.Substring(remString, i, length2 - i), culture - ) - .DoubleVal; - beyondCount = 297 + length2; - break; - } - } - - if (!found) return new Number(0.0); - } - - return (Number)OperationsOther.VaryBaseTenExponent - ( - Conversions.ConvertDoubleToNumber - ( - tempVar.DoubleVal - ), - sign * beyondCount - ); - } - } - } - - return new Number(ErrorTypesNumber.ParseError); - } - - //This method is only called after having confirmed that the given input contains "e". - private static double[] ExponentialPartsAnalysis(String input, Locale culture) - { - ArrayList tempStrings = CSharpOtherNP.SplitTryCatch(input, "e"); - if (tempStrings.size() != 2) return null; - - double[] outVals = new double[2]; - //Standard double.TryParse is fine because the input string isn't expected to fulfill the NumberP rules, but the - //standard .NET ones (i.e., double + "e" + int). - //NOTE: TryParseMethodsNP.Double emulates the double.TryParse behaviour. - TryParseOutputNP tempVar = TryParseMethodsNP.Double - ( - tempStrings.get(0), culture - ); - if (!tempVar.IsOK) return null; - outVals[0] = tempVar.DoubleVal; - - tempVar = TryParseMethodsNP.Double - ( - tempStrings.get(1), culture - ); - if - ( - !tempVar.IsOK || Math.abs(tempVar.DoubleVal) > - Conversions.ConvertTargetToDouble(Integer.MAX_VALUE) - ) - { return null; } - outVals[1] = tempVar.DoubleVal; - - return outVals; - } - - private static int GetBeyondDoubleCharacterCount(String remString, Locale culture) - { - int outCount = 0; - - try - { - for (Character item: remString.toCharArray()) - { - if - ( - !Character.isDigit(item) && !InputIsCultureFeature - ( - item.toString(), CultureFeatures.ThousandSeparator, culture - ) - ) - { return 0; } - - outCount = outCount + 1; - } - } - catch(Exception e) - { - //The really unlikely scenario of hitting Integer.MAX_VALUE. - outCount = -1; - } - - return outCount; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsCompareTo.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsCompareTo.java deleted file mode 100644 index 5b7a622..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsCompareTo.java +++ /dev/null @@ -1,110 +0,0 @@ -package InternalNumberParser.Operations; - -import InternalNumberParser.Conversions; -import InternalNumberParser.CSharpAdaptation.*; -import NumberParser.*; - -public class OperationsCompareTo -{ - static NumberX.MainVars[] tempVars = null; - - //This method is called from CompareTo of Number/NumberO instances. - public static int CompareDouble(Object thisVar, Object other) - { - int tempInt = ComparePreanalysis(thisVar, other); - if (tempInt != -2) return tempInt; - - return - ( - tempVars[0].BaseTenExponent == tempVars[1].BaseTenExponent ? - ((Double)Conversions.ConvertTargetToDouble(tempVars[0].Value)).compareTo - (Conversions.ConvertTargetToDouble(tempVars[1].Value)) : - ((Integer)tempVars[0].BaseTenExponent).compareTo - ( - tempVars[1].BaseTenExponent - ) - ); - } - - //This method is called from CompareTo of NumberD/NumberP instances. - //It always relies on the same common type (i.e., decimal) to avoid different-type-Value problems. - public static int CompareDynamic(Object thisVar, Object other) - { - int tempInt = ComparePreanalysis(thisVar, other); - if (tempInt != -2) return tempInt; - - NumberD[] adapted = ComparedInstancesToDouble(); - - return - ( - adapted[0].getBaseTenExponent() == adapted[1].getBaseTenExponent() ? - ((Double)Conversions.ConvertTargetToDouble(adapted[0].getValue())).compareTo - ((Double)Conversions.ConvertTargetToDouble(adapted[1].getValue())) : - ((Integer)adapted[0].getBaseTenExponent()).compareTo - ( - (Integer)adapted[1].getBaseTenExponent() - ) - ); - } - - //Both arguments are non-null NumberD/NumberP instances. - static NumberD[] ComparedInstancesToDouble() - { - //Decimal is the most precise type and NumberParser is an eminently-precision-focused library. - //The decimal range is notably smaller than the one of other types (e.g., double) and, consequently, - //that decision might provoke (avoidable) errors. In any case, the scenarios provoking those errors - //happen under so extreme conditions (i.e., over/under +-10^2147483647) that cannot justify the reliance - //on a less precise type. - return new NumberD[] - { - new NumberD - ( - Conversions.CastDynamicToType - ( - tempVars[0].Value, NumericTypes.Double - ), - tempVars[0].BaseTenExponent, NumericTypes.Double - ), - new NumberD - ( - Conversions.CastDynamicToType - ( - tempVars[1].Value, NumericTypes.Double - ), - tempVars[1].BaseTenExponent, NumericTypes.Double - ) - }; - } - - static int ComparePreanalysis(Object thisVar, Object other) - { - if (thisVar == null || other == null) - { - if (thisVar == null && other == null) return 0; - - return (thisVar == null ? -1 : 1); - } - - - tempVars = new NumberX.MainVars[] - { - NumberX.GetMainVars(thisVar), NumberX.GetMainVars(other) - }; - - if - ( - !tempVars[0].Error.equals(ErrorTypesNumber.None) || - !tempVars[1].Error.equals(ErrorTypesNumber.None) - ) - { - if (tempVars[0].Error.equals(tempVars[1].Error)) return 0; - - return - ( - !tempVars[0].Error.equals(ErrorTypesNumber.None) ? -1 : 1 - ); - } - - return -2; - } -} \ No newline at end of file diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsEquals.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsEquals.java deleted file mode 100644 index 1086b8c..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsEquals.java +++ /dev/null @@ -1,131 +0,0 @@ -package InternalNumberParser.Operations; - -import java.util.ArrayList; - -import NumberParser.*; -import NumberParser.Number; -import InternalNumberParser.*; -import InternalNumberParser.CSharpAdaptation.*; - - -public class OperationsEquals -{ - public static boolean NumberXsAreEqualBasic(Object first, Object second) - { - if (first == null || second == null) - { - return (first == null && second == null); - } - - NumberX.MainVars first2 = NumberX.GetMainVars(first); - NumberX.MainVars second2 = NumberX.GetMainVars(second); - if (!first2.Type.equals(second2.Type) || !first2.Error.equals(second2.Error)) - { - return false; - } - - if (first2.BaseTenExponent != 0 || second2.BaseTenExponent != 0) - { - first2 = NumberX.GetMainVars - ( - OperationsManaged.PassBaseTenToValue - ( - new NumberD(first2.Value, first2.BaseTenExponent) - ) - ); - - second2 = NumberX.GetMainVars - ( - OperationsManaged.PassBaseTenToValue - ( - new NumberD(second2.Value, second2.BaseTenExponent) - ) - ); - } - - return ValuesAreEqual(first2, second2); - } - - public static boolean NumberXsAreEqual(Number first, Number second) - { - return NumberXsAreEqualBasic(first, second); - } - - public static boolean NumberXsAreEqual(NumberD first, NumberD second) - { - return - ( - first.getType().equals(second.getType()) && - NumberXsAreEqualBasic(first, second) - ); - } - - public static boolean NumberXsAreEqual(NumberO first, NumberO second) - { - return - ( - NumberXsAreEqualBasic(first, second) && - OthersAreEqual(first.getOthers(), second.getOthers()) - ); - } - - private static boolean OthersAreEqual(ArrayList first, ArrayList second) - { - if (first.size() != second.size()) return false; - - for (NumberD item1: first) - { - NumberD item2 = LinqNP.FirstOrDefault - ( - second, x -> x.getType().equals(item1.getType()), null - ); - if (item2 == null) return false; - } - - return true; - } - - public static boolean NumberXsAreEqual(NumberP first, NumberP second) - { - return - ( - NumberXsAreEqualBasic(first, second) && - first.getOriginalString().equals(second.getOriginalString()) && - ParseConfigsAreEqual(first.getParseConfig(), second.getParseConfig()) - ); - } - - public static boolean ParseConfigsAreEqual(ParseConfig first, ParseConfig second) - { - return - ( - first.getTarget().equals(second.getTarget()) && - first.getCulture().equals(second.getCulture()) && - first.getParseType().equals(second.getParseType()) - ); - } - - public static boolean PolynomialsAreEqual(Polynomial first, Polynomial second) - { - return - ( - first.Error.equals(second.Error) && NumberXsAreEqual(first.A, second.A) && - NumberXsAreEqual(first.B, second.B) && NumberXsAreEqual(first.C, second.C) - ); - } - - private static boolean ValuesAreEqual(NumberX.MainVars first, NumberX.MainVars second) - { - return - ( - first.Value.equals(second.Value) && - ( - ErrorInfoNumber.InputTypeIsValidNumeric(first.Value).equals - ( - ErrorInfoNumber.InputTypeIsValidNumeric(second.Value) - ) - ) - && first.BaseTenExponent == second.BaseTenExponent - ); - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsMain.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsMain.java deleted file mode 100644 index ef09cef..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsMain.java +++ /dev/null @@ -1,234 +0,0 @@ -package InternalNumberParser.Operations; - -import java.util.ArrayList; -import java.util.Locale; - -import NumberParser.*; -import NumberParser.Number; -import InternalNumberParser.*; -import InternalNumberParser.CSharpAdaptation.CSharpOtherNP; -import InternalNumberParser.CSharpAdaptation.LinqNP; - -public class OperationsMain -{ - public static NumberD PerformOtherOperationD(NumberD first, NumberD second, ExistingOperations operation) - { - return PerformOtherOperationD(first, second, operation, true); - } - - public static NumberD PerformOtherOperationD(NumberD first, NumberD second, ExistingOperations operation, boolean checkError) - { - return new NumberD - ( - PerformOtherOperation - ( - new Number(first), new Number(second), operation, checkError - ) - ); - } - - public static NumberO PerformOtherOperationO(NumberO first, NumberO second, ExistingOperations operation) - { - return PerformOtherOperationO(first, second, operation, true); - } - - public static NumberO PerformOtherOperationO(NumberO first, NumberO second, ExistingOperations operation, boolean checkError) - { - return new NumberO - ( - new NumberO - ( - PerformOtherOperation - ( - new Number(first), new Number(second), operation, checkError - ) - ), - (ArrayList)LinqNP.Select - ( - first.getOthers(), x -> x.getType() - ) - ); - } - - public static NumberP PerformOtherOperationP(NumberP first, NumberP second, ExistingOperations operation) - { - return PerformOtherOperationP(first, second, operation, true); - } - - public static NumberP PerformOtherOperationP(NumberP first, NumberP second, ExistingOperations operation, boolean checkError) - { - return new NumberP - ( - PerformOtherOperation - ( - new Number(first), new Number(second), operation, checkError - ), - GetOperationString - ( - first, second, operation, first.getParseConfig().getCulture() - ), - first.getParseConfig() - ); - } - - public static Number PerformOtherOperation(Number first, Number second, ExistingOperations operation) - { - return PerformOtherOperation(first, second, operation, true); - } - - public static Number PerformOtherOperation(Number first, Number second, ExistingOperations operation, boolean checkError) - { - if (checkError) - { - ErrorTypesNumber error = ErrorInfoNumber.GetOperationError - ( - first, second, operation - ); - if (!error.equals(ErrorTypesNumber.None)) return new Number(error); - } - - Number first2 = OperationsManaged.PassBaseTenToValue(new Number(first)); - Number second2 = OperationsManaged.PassBaseTenToValue(new Number(second)); - - Number numberOut = new Number(); - - if (operation.equals(ExistingOperations.Modulo)) - { - if (first2.getBaseTenExponent() == 0 && second2.getBaseTenExponent() == 0) - { - return new Number(first2.getValue() % second2.getValue()); - } - - numberOut = new Number - ( - OperationsManaged.SubtractInternal - ( - new NumberD(first2), OperationsManaged.MultiplyInternal - ( - Math2.Floor - ( - new NumberD - ( - OperationsManaged.DivideInternal - ( - first2, second2 - ) - ) - ), - new NumberD(second2) - ) - ) - ); - } - else - { - numberOut.setValue - ( - GetComparisonResult - ( - first2, second2, operation - ) - ); - } - - return OperationsManaged.PassBaseTenToValue(numberOut); - } - - static double GetComparisonResult(Number first, Number second, ExistingOperations operation) - { - if (first.getBaseTenExponent() != second.getBaseTenExponent()) - { - if (operation.equals(ExistingOperations.GreaterOrEqual)) - { - if (first.getBaseTenExponent() >= second.getBaseTenExponent()) - { - return 1.0; - } - } - else if (operation.equals(ExistingOperations.Greater)) - { - if (first.getBaseTenExponent() > second.getBaseTenExponent()) - { - return 1.0; - } - } - else if (operation.equals(ExistingOperations.SmallerOrEqual)) - { - if (first.getBaseTenExponent() <= second.getBaseTenExponent()) - { - return 1.0; - } - } - else if (operation.equals(ExistingOperations.Smaller)) - { - if (first.getBaseTenExponent() < second.getBaseTenExponent()) - { - return 1.0; - } - } - } - else - { - if (operation.equals(ExistingOperations.GreaterOrEqual)) - { - if (first.getValue() >= second.getValue()) - { - return 1.0; - } - } - else if (operation.equals(ExistingOperations.Greater)) - { - if (first.getValue() > second.getValue()) - { - return 1.0; - } - } - else if (operation.equals(ExistingOperations.SmallerOrEqual)) - { - if (first.getValue() <= second.getValue()) - { - return 1.0; - } - } - else if (operation.equals(ExistingOperations.Smaller)) - { - if (first.getValue() < second.getValue()) - { - return 1.0; - } - } - } - - return 0.0; - } - - public static String GetOperationString - ( - Object first, Object second, ExistingOperations operation, Locale culture - ) - { - return - ( - //It doesn't matter whether first/second are NumberX variables or values, because all the NumberX classes - //have their own ToString(CultureInfo) methods. - CSharpOtherNP.SpecificDoubleOrNumberXToString(first, culture) - + " " + GetOperationSymbol(operation) + " " + - CSharpOtherNP.SpecificDoubleOrNumberXToString(second, culture) - ); - } - - static String GetOperationSymbol(ExistingOperations operation) - { - if (operation.equals(ExistingOperations.Addition)) return "+"; - if (operation.equals(ExistingOperations.Subtraction)) return "-"; - if (operation.equals(ExistingOperations.Multiplication)) return "*"; - if (operation.equals(ExistingOperations.Division)) return "/"; - if (operation.equals(ExistingOperations.GreaterOrEqual)) return ">="; - if (operation.equals(ExistingOperations.Greater)) return ">"; - if (operation.equals(ExistingOperations.SmallerOrEqual)) return "<="; - if (operation.equals(ExistingOperations.Smaller)) return "<"; - if (operation.equals(ExistingOperations.Modulo)) return "%"; - - return ""; - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsManaged.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsManaged.java deleted file mode 100644 index 8b7a9a0..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsManaged.java +++ /dev/null @@ -1,926 +0,0 @@ -package InternalNumberParser.Operations; - -import NumberParser.*; -import NumberParser.Number; -import InternalNumberParser.*; -import InternalNumberParser.CSharpAdaptation.*; -import InternalNumberParser.Math2Internal.*; - -public class OperationsManaged -{ - public static NumberP PerformArithmeticOperation - ( - NumberP first, NumberP second, ExistingOperations operation - ) - { - return PerformArithmeticOperation - ( - first, second, operation, true - ); - } - - public static NumberP PerformArithmeticOperation - ( - NumberP first, NumberP second, - ExistingOperations operation, boolean baseTenToValue - ) - { - return new NumberP - ( - PerformArithmeticOperation - ( - new Number(first), new Number(second), operation - ), - OperationsMain.GetOperationString - ( - first, second, operation, - first.getParseConfig().getCulture() - ), - first.getParseConfig() - ); - } - - public static NumberO PerformArithmeticOperation - ( - NumberO first, NumberO second, ExistingOperations operation - ) - { - return PerformArithmeticOperation - ( - first, second, operation, true - ); - } - - public static NumberO PerformArithmeticOperation - ( - NumberO first, NumberO second, - ExistingOperations operation, - boolean baseTenToValue - ) - { - return new NumberO - ( - new NumberO - ( - PerformArithmeticOperation - ( - new Number(first), new Number(second), operation - ) - ), - LinqNP.Select(first.getOthers(), x -> x.getType()) - ); - } - - public static NumberD PerformArithmeticOperation - ( - NumberD first, NumberD second, ExistingOperations operation - ) - { - return PerformArithmeticOperation - ( - first, second, operation, true - ); - } - - public static NumberD PerformArithmeticOperation - ( - NumberD first, NumberD second, ExistingOperations operation, boolean baseTenToValue - ) - { - Number number = PerformArithmeticOperation - ( - new Number(first), new Number(second), operation - ); - - return - ( - !number.getError().equals(ErrorTypesNumber.None) ? - new NumberD(number.getError()) : new NumberD - ( - number.getValue(), number.getBaseTenExponent(), first.getType() - ) - ); - } - - public static Number PerformArithmeticOperation - ( - Number first, double second, ExistingOperations operation - ) - { - return PerformArithmeticOperation(first, second, operation, true); - } - - public static Number PerformArithmeticOperation - ( - Number first, double second, ExistingOperations operation, boolean baseTenToValue - ) - { - return PerformArithmeticOperation - ( - first, new Number(second), operation - ); - } - - public static Number MultiplyInternal(Number first, Number second) - { - return PerformArithmeticOperation - ( - first, second, ExistingOperations.Multiplication, false - ); - } - - public static NumberD MultiplyInternal(NumberD first, NumberD second) - { - return PerformArithmeticOperation - ( - first, second, ExistingOperations.Multiplication, false - ); - } - - public static Number DivideInternal(Number first, Number second) - { - return PerformArithmeticOperation - ( - first, second, ExistingOperations.Division, false - ); - } - - public static NumberD DivideInternal(NumberD first, NumberD second) - { - return PerformArithmeticOperation - ( - first, second, ExistingOperations.Division, false - ); - } - - public static Number AddInternal(Number first, Number second) - { - return PerformArithmeticOperation - ( - first, second, ExistingOperations.Addition, false - ); - } - - public static NumberD AddInternal(NumberD first, NumberD second) - { - return PerformArithmeticOperation - ( - first, second, ExistingOperations.Addition, false - ); - } - - public static NumberD SubtractInternal(NumberD first, NumberD second) - { - return PerformArithmeticOperation - ( - first, second, ExistingOperations.Subtraction, false - ); - } - - public static Number PerformArithmeticOperation - ( - Number first, Number second, ExistingOperations operation - ) - { - return PerformArithmeticOperation(first, second, operation, true); - } - - public static Number PerformArithmeticOperation - ( - Number first, Number second, ExistingOperations operation, boolean baseTenToValue - ) - { - ErrorTypesNumber error = ErrorInfoNumber.GetOperationError - ( - first, second, operation - ); - if (!error.equals(ErrorTypesNumber.None)) return new Number(error); - - Number outNumber = - ( - operation.equals(ExistingOperations.Addition) || - operation.equals(ExistingOperations.Subtraction) ? - PerformManagedOperationAddition - ( - new Number(first), new Number(second), operation - ) : - PerformManagedOperationMultiplication - ( - new Number(first), new Number(second), operation - ) - ); - - return - ( - baseTenToValue ? PassBaseTenToValue(outNumber, true) : outNumber - ); - } - - static Number PerformManagedOperationAddition(Number first, Number second, ExistingOperations operation) - { - return PerformManagedOperationNormalisedValues - ( - first, - //In addition/subtraction, the normalised operands might require further modifications. That's why - //calling a specific method rather than the generic NormaliseNumber. - GetOperandsAddition(first, second, operation), - operation - ); - } - - static Number[] GetOperandsAddition(Number first, Number second, ExistingOperations operation) - { - Number[] operands = new Number[] - { - NormaliseNumber(first), NormaliseNumber(second) - }; - - return - ( - operands[0].getBaseTenExponent() != operands[1].getBaseTenExponent() ? - //The addition/subtraction might not be performed right away even with normalised values. - AdaptNormalisedValuesForAddition(operands, operation) : operands - ); - } - - static Number[] AdaptNormalisedValuesForAddition(Number[] operands, ExistingOperations operation) - { - if (operands[0].getBaseTenExponent() == operands[1].getBaseTenExponent()) - { - //Having the same BaseTenExponent means that the given operation can be performed right away. - return operands; - } - - int[] bigSmallI = - ( - operands[0].getBaseTenExponent() > - operands[1].getBaseTenExponent() ? - new int[] { 0, 1 } : new int[] { 1, 0 } - ); - - //Only the variable with the bigger value is modified. For example: 5*10^5 & 3*10^3 is converted - //into 500*10^3 & 3*10^3 in order to allow the addition 500 + 3. - Number big2 = AdaptBiggerAdditionOperand(operands, bigSmallI, operation); - - if (!big2.getError().equals(ErrorTypesNumber.None)) - { - return TooBigGapAddition(operands, bigSmallI, operation); - } - - operands[bigSmallI[0]].setValue(big2.getValue()); - operands[bigSmallI[0]].setBaseTenExponent - ( - operands[bigSmallI[1]].getBaseTenExponent() - ); - - return operands; - } - - //When adding/subtracting two numbers whose gap is bigger than the maximum decimal precision, there - //is no need to perform any operation (no change will be observed anyway). This method takes care - //of these cases and returns the expected output (i.e., biggest value). - static Number[] TooBigGapAddition(Number[] operands, int[] bigSmallI, ExistingOperations operation) - { - Number[] outOperands = new Number[] - { - //First operand together with the numeric information (i.e., Value and BaseTenExponent) which - //is associated with the biggest one. - new Number(operands[0]) - }; - - outOperands[0].setValue(operands[bigSmallI[0]].getValue()); - outOperands[0].setBaseTenExponent(operands[bigSmallI[0]].getBaseTenExponent()); - - if (operation.equals(ExistingOperations.Subtraction) && bigSmallI[0] == 1) - { - outOperands[0].setValue(-1.0 * outOperands[0].getValue()); - } - - return outOperands; - } - - static Number AdaptBiggerAdditionOperand(Number[] operands, int[] bigSmallI, ExistingOperations operation) - { - int gapExponent = - ( - operands[bigSmallI[0]].getBaseTenExponent() - - operands[bigSmallI[1]].getBaseTenExponent() - ); - - if (gapExponent >= 27) - { - //The difference between both inputs is bigger than (or, at least, very close to) the maximum decimal value/precision; - //what makes this situation calculation unworthy and the first operand to be returned as the result. - //Note that the error below these lines is just an easy way to tell the calling function about this eventuality. - return new Number - ( - ErrorTypesNumber.NumericOverflow - ); - } - - //PerformArithmeticOperationValues is used to make sure that the resulting numeric information is stored - //in Value (if possible). - Number big2 = PerformArithmeticOperationValues - ( - Math2PowSqrt.PowSqrtInternal(new Number(10.0), gapExponent, false), - new Number(operands[bigSmallI[0]].getValue()), - ExistingOperations.Multiplication - ); - - boolean isWrong = - ( - !big2.getError().equals(ErrorTypesNumber.None) || big2.getBaseTenExponent() != 0 ? - - //The value of the bigger input times 10^(gap between BaseTenExponent of inputs) is too big. - isWrong = true : - - //Overflow-check very unlikely to trigger an error. - AreAdditionFinalValuesWrong - ( - operands[0].getValue(), operands[1].getValue(), operation - ) - ); - - return - ( - isWrong ? - //This error is just an easy way to let the calling function know about the fact that no - //calculation has been performed (too big gap). This isn't a properly-speaking error and - //that's why it will not be notified to the user. - new Number(ErrorTypesNumber.InvalidInput) : - //Returning the new big value. For example: with 5*10^4 & 3*10^2, 500 would be returned. - new Number(operands[bigSmallI[0]]) - {{ - setValue(big2.getValue()); - }} - ); - } - - static boolean AreAdditionFinalValuesWrong(double val1, double val2, ExistingOperations operation) - { - boolean isWrong = false; - - try - { - val1 = val1 + val2 * - ( - operation == ExistingOperations.Addition ? 1 : -1 - ); - } - catch(Exception e) { isWrong = true; } - - return isWrong; - } - - static Number PerformManagedOperationMultiplication(Number first, Number second, ExistingOperations operation) - { - return PerformManagedOperationNormalisedValues - ( - first, new Number[] - { - NormaliseNumber(first), NormaliseNumber(second) - }, - operation - ); - } - - static Number PerformManagedOperationNormalisedValues(Number outInfo, Number[] normalised, ExistingOperations operation) - { - return - ( - normalised.length == 1 ? - //There is just one operand when the difference between both of them is too big. - outInfo = normalised[0] : - PerformManagedOperationTwoOperands(outInfo, normalised, operation) - ); - } - - static Number PerformManagedOperationTwoOperands(Number outNumber, Number[] normalised, ExistingOperations operation) - { - if (!outNumber.getError().equals(ErrorTypesNumber.None)) return new Number(outNumber); - - Number tempNumber = PerformArithmeticOperationValues - ( - normalised[0], normalised[1], operation - ); - if (!tempNumber.getError().equals(ErrorTypesNumber.None)) return tempNumber; - - - outNumber.setBaseTenExponent(tempNumber.getBaseTenExponent()); - outNumber.setValue(tempNumber.getValue()); - - return outNumber; - } - - static Number PerformArithmeticOperationValues(Number first, Number second, ExistingOperations operation) - { - if (first.getValue() == 0.0 || second.getValue() == 0.0) - { - if - ( - operation.equals(ExistingOperations.Multiplication) || - operation.equals(ExistingOperations.Division) - ) - { - //Dividing by zero scenarios are taken care of somewhere else. - return new Number(first) {{ setValue(0.0); }}; - } - } - - Number output = new Number(first); - Number first2 = new Number(first); - Number second2 = new Number(second); - - boolean isWrong = false; - try - { - if (operation.equals(ExistingOperations.Addition)) - { - output.setValue(output.getValue() + second2.getValue()); - } - else if (operation.equals(ExistingOperations.Subtraction)) - { - output.setValue(output.getValue() - second.getValue()); - } - else - { - //The reason for checking whether BaseTenExponent is inside/outside the int range before performing - //the operation (rather than going ahead and eventually catching the resulting exception) isn't just - //being quicker, but also the only option in many situations. Note that an addition/subtraction between - //two int variables whose result is outside the int range might not trigger an exception (+ random - //negative value as output). - Number tempVar = (Number)OperationsOther.VaryBaseTenExponent - ( - output, second.getBaseTenExponent(), - operation.equals(ExistingOperations.Division) - ); - if (!tempVar.getError().equals(ErrorTypesNumber.None)) return tempVar; - - if (operation.equals(ExistingOperations.Multiplication)) - { - output.setValue(output.getValue() * second2.getValue()); - output.setBaseTenExponent - ( - output.getBaseTenExponent() + second2.getBaseTenExponent() - ); - } - else if (operation.equals(ExistingOperations.Division)) - { - if (second.getValue() == 0.0) - { - return new Number(ErrorTypesNumber.InvalidOperation); - } - output.setValue(output.getValue() / second2.getValue()); - output.setBaseTenExponent - ( - output.getBaseTenExponent() - - second2.getBaseTenExponent() - ); - } - } - } - catch(Exception e) { isWrong = true; } - - return - ( - //An exception might not be triggered despite of dealing with numbers outside decimal precision. - //For example: 0.00000000000000000001m * 0.0000000000000000000001m can plainly output 0m. - isWrong || - ( - ( - operation.equals(ExistingOperations.Multiplication) || - operation.equals(ExistingOperations.Division) - ) - && output.getValue() == 0.0 - ) - ? OperationValuesManageError(first2, second2, operation) : output - ); - } - - static Number OperationValuesManageError(Number outNumber, Number second, ExistingOperations operation) - { - Number tempVar = OperationValuesManageErrorPreAnalysis(outNumber, second, operation); - if (tempVar != null) return tempVar; - - Number second2 = new Number(Math.abs(second.getValue())); - second2 = FromValueToBaseTenExponent - ( - second2.getValue(), second2.getBaseTenExponent() - ); - - outNumber = (Number)OperationsOther.VaryBaseTenExponent - ( - outNumber, - ( - operation.equals(ExistingOperations.Multiplication) ? 1 : -1 - ) - * second2.getBaseTenExponent() - ); - - if (Math.abs(second2.getValue()) == 1.0) return outNumber; - - try - { - outNumber = PerformArithmeticOperation - ( - outNumber, second2.getValue(), operation - ); - } - catch (Exception e) - { - Number outNumber1 = new Number(outNumber); - outNumber1.setValue(second2.getValue()); - outNumber1.setBaseTenExponent(0); - - Number outNumber2 = new Number(); - outNumber2.setValue(outNumber.getValue()); - outNumber2.setBaseTenExponent - ( - outNumber.getBaseTenExponent() - ); - - outNumber = OperationValuesManageError - ( - outNumber1, outNumber2, operation - ); - } - - return outNumber; - } - - static Number OperationValuesManageErrorPreAnalysis(Number outNumber, Number second, ExistingOperations operation) - { - if (!operation.equals(ExistingOperations.Multiplication) && !operation.equals(ExistingOperations.Division)) - { - //This condition should never be true on account of the fact that the pre-modifications performed before - //adding/subtracting should avoid erroneous situations. - return new Number(ErrorTypesNumber.NumericOverflow); - } - - //Accounting for some limit cases which might reach this point and provoke and infinite set of recursive calls. - if - ( - operation.equals(ExistingOperations.Multiplication) && Math.abs - ( - outNumber.getBaseTenExponent() + second.getBaseTenExponent() - ) - == Integer.MAX_VALUE - ) - { - return new Number(ErrorTypesNumber.NumericOverflow); - } - - if - ( - operation.equals(ExistingOperations.Division) && - ( - outNumber.getBaseTenExponent() - - second.getBaseTenExponent() - ) - == Integer.MIN_VALUE - ) - { - return new Number(ErrorTypesNumber.NumericOverflow); - } - - return null; - } - - //This method is called when performing an arithmetic operation between two variables of a random - //numeric type (i.e., dynamic numeric variable) and makes sure that the output type matches the - //one of the inputs. Note that, in some cases, an operation between two variables of the same type - //might output a different one (e.g., sbyte * sbyte = int). - //This method assumes that both inputs are non-null and belong to the same numeric type. - static Object PerformArithmeticOperationDynamicVariables(Object var1, Object var2, ExistingOperations operation) - { - return Conversions.CastDynamicToType - ( - PerformArithmeticOperationDynamicVariablesValues - ( - var1, var2, operation - ), - NumericTypesMethods.GetTypeFromObject(var1) - ); - } - - static Object PerformArithmeticOperationDynamicVariablesValues(Object var1, Object var2, ExistingOperations operation) - { - double var11 = Conversions.ConvertTargetToDouble(var1); - double var22 = Conversions.ConvertTargetToDouble(var2); - - if (operation.equals(ExistingOperations.Multiplication)) - { - return Conversions.CastDynamicToType - ( - var11 * var22, - NumericTypesMethods.GetTypeFromObject - ( - var1 - ) - ); - } - else if (operation.equals(ExistingOperations.Division)) - { - return Conversions.CastDynamicToType - ( - var11 / var22, - NumericTypesMethods.GetTypeFromObject - ( - var1 - ) - ); - } - else if (operation.equals(ExistingOperations.Addition)) - { - return Conversions.CastDynamicToType - ( - var11 + var22, - NumericTypesMethods.GetTypeFromObject - ( - var1 - ) - ); - } - else if (operation.equals(ExistingOperations.Subtraction)) - { - return Conversions.CastDynamicToType - ( - var11 - var22, - NumericTypesMethods.GetTypeFromObject - ( - var1 - ) - ); - } - - return null; - } - - public static NumberD PassBaseTenToValue(NumberD input) - { - return PassBaseTenToValue(input, false); - } - - public static NumberD PassBaseTenToValue(NumberD input, boolean showUser) - { - NumberD output = new NumberD(input); - if (input.getBaseTenExponent() == 0) return output; - - output = OperationsOther.AbsInternal(output); - if (!output.getError().equals(ErrorTypesNumber.None)) - { - //Although it is extremely unlikely, calculating the absolute value might provoke to go beyond the - //maximum supported range (i.e., BaseTenExponent outside the int range). - return new NumberD(ErrorTypesNumber.InvalidOperation); - } - - if (showUser && Conversions.ConvertTargetToDouble(output.getValue()) < 1.0) - { - //The opposite to passing to value, but what is expected anyway. - return NormaliseNumber(input); - } - - boolean decrease = input.getBaseTenExponent() > 0; - double sign = Conversions.ConvertTargetToDouble - ( - PerformArithmeticOperationDynamicVariables - ( - Conversions.ConvertTargetToDouble(input.getValue()), - Conversions.ConvertTargetToDouble(output.getValue()), - ExistingOperations.Division - ) - ); - - //Apparently, the precision problems of the (Java) Double type appear more easily with - //divisions. That's why I am including here two variations, rather than one like in the C# - //version: to rely on multiplications in all the possible scenarios. - double varMult = 10.0; - double varDiv = 0.1; - double one = 1.0; - - while (output.getBaseTenExponent() != 0) - { - if (decrease) - { - if - ( - Conversions.ConvertTargetToDouble(output.getValue()) > - Conversions.ConvertTargetToDouble - ( - Basic.AllNumberMinMaxPositives.get - ( - output.getType() - ) - .get(1) - ) - * varDiv - ) - { break; } - - output.setValue - ( - PerformArithmeticOperationDynamicVariables - ( - output.getValue(), varMult, - ExistingOperations.Multiplication - ) - ); - - output.setBaseTenExponent - ( - output.getBaseTenExponent() - 1 - ); - } - else - { - if - ( - ( - showUser && Conversions.ConvertTargetToDouble - (output.getValue()) * varDiv < one - ) - || - Conversions.ConvertTargetToDouble(output.getValue()) < - Conversions.ConvertTargetToDouble - ( - Basic.AllNumberMinMaxPositives.get - ( - output.getType() - ) - .get(0) - ) - * varMult - ) - { break; } - - output.setValue - ( - PerformArithmeticOperationDynamicVariables - ( - output.getValue(), varDiv, - ExistingOperations.Multiplication - ) - ); - - output.setBaseTenExponent - ( - output.getBaseTenExponent() + 1 - ); - } - } - - output.setValue - ( - PerformArithmeticOperationDynamicVariables - ( - output.getValue(), sign, - ExistingOperations.Multiplication - ) - ); - - return output; - } - - public static Number PassBaseTenToValue(Number input) - { - return PassBaseTenToValue(input, false); - } - - public static Number PassBaseTenToValue(Number input, boolean showUser) - { - Number output = new Number(input); - if (input.getBaseTenExponent() == 0) return output; - - double absValue = Math.abs(output.getValue()); - - if (showUser && absValue < 1.0) - { - //The opposite to passing to value, but what is expected anyway. - return NormaliseNumber(output); - } - - boolean decrease = output.getBaseTenExponent() > 0; - double sign = output.getValue() / absValue; - output.setValue(absValue); - - while (output.getBaseTenExponent() != 0) - { - if (decrease) - { - if - ( - output.getValue() > - (double)Basic.AllNumberMinMaxPositives.get - ( - NumericTypes.Double - ) - .get(1) / 10.0 - ) - { break; } - - output.setValue(output.getValue() * 10.0); - output.setBaseTenExponent(output.getBaseTenExponent() - 1); - } - else - { - if - ( - (showUser && output.getValue() / 10.0 < 1.0) || - output.getValue() < (double)Basic.AllNumberMinMaxPositives.get - ( - NumericTypes.Double - ) - .get(0) * 10.0 - ) - { break; } - - output.setValue(output.getValue() / 10.0); - output.setBaseTenExponent(output.getBaseTenExponent() + 1); - } - } - - output.setValue(output.getValue() * sign); - - return output; - } - - static NumberD NormaliseNumber(NumberD numberD) - { - if (numberD.getBaseTenExponent() == Integer.MAX_VALUE) - { - return new NumberD(numberD); - } - - Number tempVar = new Number(numberD); - tempVar = FromValueToBaseTenExponent - ( - tempVar.getValue(), tempVar.getBaseTenExponent(), - Basic.AllDecimalTypes.contains(numberD.getType()) - ); - - return new NumberD - ( - tempVar.getValue(), tempVar.getBaseTenExponent(), numberD.getType() - ); - } - - static Number NormaliseNumber(Number number) - { - Number outNumber = new Number(number); - if (outNumber.getBaseTenExponent() == Integer.MAX_VALUE) - { - return outNumber; - } - - return FromValueToBaseTenExponent - ( - outNumber.getValue(), outNumber.getBaseTenExponent() - ); - } - - static Number FromValueToBaseTenExponent(double value, int baseTenExponent) - { - return FromValueToBaseTenExponent(value, baseTenExponent, true); - } - - static Number FromValueToBaseTenExponent(double value, int baseTenExponent, boolean decimals) - { - Number outNumber = new Number(value, baseTenExponent); - if (value == 0.0) return outNumber; - - double valueAbs = Math.abs(value); - boolean decrease = (valueAbs > 1.0); - - while - ( - valueAbs != 1.0 && - ( - (decrease && outNumber.getBaseTenExponent() <= Integer.MAX_VALUE - 1) || - (!decrease && outNumber.getBaseTenExponent() >= Integer.MIN_VALUE + 1) - ) - ) - { - if ((decrease && valueAbs < 10.0) || (!decrease && valueAbs >= 1.0)) - { - return outNumber; - } - - value = (decrease ? value / 10.0 : value * 10.0); - if (!decimals && Math.floor(value) != value) - { - return outNumber; - } - - outNumber.setValue(value); - outNumber.setBaseTenExponent - ( - outNumber.getBaseTenExponent() + - (decrease ? 1 : -1) - ); - - valueAbs = Math.abs(value); - } - - return outNumber; - } -} \ No newline at end of file diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsOther.java b/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsOther.java deleted file mode 100644 index 914d600..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/Operations/OperationsOther.java +++ /dev/null @@ -1,168 +0,0 @@ -package InternalNumberParser.Operations; - -import java.util.Locale; - -import NumberParser.*; -import InternalNumberParser.*; -import InternalNumberParser.CSharpAdaptation.*; - -@SuppressWarnings("rawtypes") -public class OperationsOther -{ - public static String PrintNumberXInfo(Object value, Integer baseTenExponent, NumericTypes type, Locale culture) - { - String outString = OperationsOther.PrintDynamicValue(value, culture) + - ( - baseTenExponent != 0 ? "*10^" + baseTenExponent.toString() : "" - ); - - if (type != null) - { - outString += " (" + type.toString() + ")"; - } - - return outString; - } - - public static Object VaryBaseTenExponent(Object input, int baseTenIncrease) - { - return VaryBaseTenExponent(input, baseTenIncrease, false); - } - - //This method assumes that input is a valid instance of Number, NumberD, NumberO or NumberP. - public static Object VaryBaseTenExponent(Object input, int baseTenIncrease, boolean isDivision) - { - NumberX.MainVars mainVars = NumberX.GetMainVars(input); - long val1 = mainVars.BaseTenExponent; - long val2 = baseTenIncrease; - - if (isDivision) - { - //Converting a negative value into positive might provoke an overflow error for the int type - //(e.g., Math.Abs(int.MinValue)). Converting both variables to long is a quick and effective - //way to avoid this problem. - val2 *= -1; - } - - return - ( - (val2 > 0 && val1 > Integer.MAX_VALUE - val2) || - (val2 < 0 && val1 < Integer.MIN_VALUE - val2) ? - ErrorInfoNumber.GetNumberXError - ( - input.getClass(), ErrorTypesNumber.NumericOverflow - ) : - Constructors.InitialiseNumberX - ( - input.getClass(), mainVars.Value, (int)(val1 + val2) - ) - ); - } - - //This method assumes that the input culture isn't null. - public static String PrintDynamicValue(Object value, Locale culture) - { - if (value == null) return ""; - NumericTypes type = NumericTypesMethods.GetTypeFromObject(value); - if (type.equals(NumericTypes.None)) return ""; - - String output = CSharpOtherNP.NumericValueToString - ( - value, culture, type - ); - - return - ( - type.equals(NumericTypes.Character) ? - "'" + output + "'" : output - ); - } - - public static NumberD AbsInternal(Object input) - { - Class type = ErrorInfoNumber.InputTypeIsValidNumericOrNumberX(input); - - return - ( - type == null ? - new NumberD(ErrorTypesNumber.InvalidInput) : - AbsInternalValue(new NumberD(input)) - ); - } - - static NumberD AbsInternalValue(NumberD numberD) - { - if (Basic.AllUnsignedTypes.contains(numberD.getType())) - { - return numberD; - } - - if (IsSpecialAbsCase(numberD.getValue(), numberD.getType())) - { - //In certain cases, the minimum value of a type is bigger than the - //maximum one. That's why a modification is required before calculating - //the absolute value. - if (numberD.getBaseTenExponent() == Integer.MAX_VALUE) - { - return new NumberD(ErrorTypesNumber.InvalidInput); - } - - numberD.setValue - ( - Basic.GetNumberSpecificType - ( - Conversions.ConvertTargetToDouble - ( - numberD.getValue() - ) - / 10.0, numberD.getType() - ) - - ); - numberD.setBaseTenExponent - ( - numberD.getBaseTenExponent() + 1 - ); - } - - - numberD.setValue - ( - OperationsManaged.PerformArithmeticOperationDynamicVariables - ( - numberD.getValue(), Conversions.CastDynamicToType - ( - Conversions.ConvertTargetToDouble - ( - numberD.getValue() - ) - < 0.0 ? -1 : 1, numberD.getType() - ), - ExistingOperations.Multiplication - ) - ); - - return numberD; - } - - static boolean IsSpecialAbsCase(Object value, NumericTypes type) - { - return - ( - ( - type.equals(NumericTypes.Integer) && - value == Basic.AllNumberMinMaxs.get(type).get(0) - ) - || - ( - type.equals(NumericTypes.Long) && - value == Basic.AllNumberMinMaxs.get(type).get(0) - ) - || - ( - type.equals(NumericTypes.Short) && - value == Basic.AllNumberMinMaxs.get(type).get(0) - ) - ); - } -} diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/OtherParts/OtherPartsUnitParser.java b/all_code/NumberParser/src_Internal/InternalNumberParser/OtherParts/OtherPartsUnitParser.java deleted file mode 100644 index dd67c46..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/OtherParts/OtherPartsUnitParser.java +++ /dev/null @@ -1,81 +0,0 @@ -package InternalNumberParser.OtherParts; - -import java.lang.reflect.Method; - -/** -Class emulating UnitParser's UnitP in its most basic configuration, by only including the -public properties which are relevant (i.e., used by the methods in OtherPartsUnitParserMethods). -*/ -public class OtherPartsUnitParser -{ - public ErrorClass Error; - public PrefixClass UnitPrefix; - public double Value; - public int BaseTenExponent; - - public class ErrorClass - { - public String Type = "None"; - - public ErrorClass(Object unitP) throws Exception - { - if (unitP != null) - { - Object tempVar = GetUnitPProperty(unitP, "getError"); - Type = GetUnitPProperty(tempVar, "getType").toString(); - } - } - } - - public class PrefixClass - { - public double Factor = 1.0; - - public PrefixClass(Object unitP) throws Exception - { - if (unitP != null) - { - Object tempVar = GetUnitPProperty(unitP, "getUnitPrefix"); - if (tempVar != null) - { - Factor = (double)GetUnitPProperty(tempVar, "getFactor"); - } - } - } - } - - //This constructor expects a non-null UnitParser's UnitP instance. - public OtherPartsUnitParser(Object unitP) - { - try - { - Error = new ErrorClass(unitP); - if (!Error.Type.equals("None")) return; - UnitPrefix = new PrefixClass(unitP); - Value = (double)GetUnitPProperty(unitP, "getValue"); - BaseTenExponent = (int)GetUnitPProperty(unitP, "getBaseTenExponent"); - } - catch (Exception e) - { - //This point will never be reached. - //This try...catch statement is forced by the Java compiler. - } - } - - static Object GetUnitPProperty(Object numberX, String methodName) - { - try - { - Method method = numberX.getClass().getMethod(methodName); - - return method.invoke(numberX); - } - catch (Exception e) - { - //This point will never be reached. - //This try...catch statement is forced by the Java compiler. - } - - return null; - } -} \ No newline at end of file diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/OtherParts/OtherPartsUnitParserMethods.java b/all_code/NumberParser/src_Internal/InternalNumberParser/OtherParts/OtherPartsUnitParserMethods.java deleted file mode 100644 index 7a5844d..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/OtherParts/OtherPartsUnitParserMethods.java +++ /dev/null @@ -1,46 +0,0 @@ -package InternalNumberParser.OtherParts; - -import InternalNumberParser.Operations.*; -import NumberParser.*; -import NumberParser.Number; - -/** -Class including all the required resources to extract the main information of UnitP -(i.e., the main UnitParser class) variables without including a proper definition of that class. -**/ -public class OtherPartsUnitParserMethods -{ - public static Number GetNumberFromUnitP(Object unitP) - { - if (unitP == null || !unitP.getClass().getName().equals("UnitParser.UnitP")) - { - return new Number(ErrorTypesNumber.InvalidInput); - } - - OtherPartsUnitParser tempVar = new OtherPartsUnitParser - ( - unitP - ); - - return - ( - !tempVar.Error.Type.toString().equals("None") ? new Number - ( - ErrorTypesNumber.InvalidInput - ) - : UnitPToNumber(tempVar) - ); - } - - private static Number UnitPToNumber(OtherPartsUnitParser unitP) - { - return - ( - OperationsManaged.MultiplyInternal - ( - new Number(unitP.UnitPrefix.Factor), - new Number(unitP.Value, unitP.BaseTenExponent) - ) - ); - } -} \ No newline at end of file diff --git a/all_code/NumberParser/src_Internal/InternalNumberParser/ParseInfo.java b/all_code/NumberParser/src_Internal/InternalNumberParser/ParseInfo.java deleted file mode 100644 index fa3afb2..0000000 --- a/all_code/NumberParser/src_Internal/InternalNumberParser/ParseInfo.java +++ /dev/null @@ -1,30 +0,0 @@ -package InternalNumberParser; - -import NumberParser.*; -import NumberParser.Number; - -public class ParseInfo -{ - public String OriginalString = null; - public Number Number = null; - public ParseConfig Config = null; - - public ParseInfo(NumberP numberP) - { - OriginalString = numberP.getOriginalString(); - Config = new ParseConfig(numberP.getParseConfig()); - Number = new Number(); - } - - public ParseInfo(ParseInfo info) - { - this(info, ErrorTypesNumber.None); - } - - public ParseInfo(ParseInfo info, ErrorTypesNumber error) - { - OriginalString = info.OriginalString; - Config = new ParseConfig(info.Config); - Number = new Number(error); - } -} diff --git a/all_code/NumberParser/src_Public/NumberParser/ErrorTypesNumber.java b/all_code/NumberParser/src_Public/NumberParser/ErrorTypesNumber.java deleted file mode 100644 index 46142f4..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/ErrorTypesNumber.java +++ /dev/null @@ -1,18 +0,0 @@ -package NumberParser; - -/**Contains all the supported error types.**/ -public enum ErrorTypesNumber -{ - /**No error.**/ - None, - /**Error provoked by not matching the expected input format (e.g., null string).**/ - InvalidInput, - /**Error provoked by not matching the expected conditions of certain mathematical operation (e.g., division by zero).**/ - InvalidOperation, - /**Error provoked by not matching the expected conditions of the corresponding native System.Math method.**/ - NativeMethodError, - /**Error provoked by a calculation outputting a value outside the supported range (i.e., BaseTenExponent outside the int range).**/ - NumericOverflow, - /**Error provoked by a string not containing valid numeric information under the given conditions.**/ - ParseError -} diff --git a/all_code/NumberParser/src_Public/NumberParser/Math2.java b/all_code/NumberParser/src_Public/NumberParser/Math2.java deleted file mode 100644 index 2ef1511..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/Math2.java +++ /dev/null @@ -1,648 +0,0 @@ -package NumberParser; - -import java.util.ArrayList; - -import InternalNumberParser.*; -import InternalNumberParser.CSharpAdaptation.*; -import InternalNumberParser.Math2Internal.*; -import InternalNumberParser.Operations.*; - -/**Math2 contains all the mathematical resources of NumberParser**/ -@SuppressWarnings("serial") -public class Math2 -{ - //---------------------------- All the public existing methods (mixture of Java and .NET). - - /** - NumberD-adapted version of Math.abs. - @param n Input value. - **/ - public static NumberD Abs(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Abs - ); - } - - /** - NumberD-adapted version of Math.acos. - @param n Input values. - **/ - public static NumberD Acos(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Acos - ); - } - - /** - NumberD-adapted version of Math.asin. - @param n Input value. - **/ - public static NumberD Asin(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Asin - ); - } - - /** - NumberD-adapted version of Math.atan. - @param n Input value. - **/ - public static NumberD Atan(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Atan - ); - } - - /** - NumberD-adapted version of Math.atan2. - @param n1 First value. - @param n2 Second value. - **/ - public static NumberD Atan2(NumberD n1, NumberD n2) - { - return Math2Existing.PerformOperationTwoOperands - ( - n1, n2 , ExistingOperations.Atan2 - ); - } - - /** - NumberD-adapted version of .NET System.Math.BigMul. - @param n1 First value to multiply. - @param n2 Second value to multiply. - **/ - public static NumberD BigMul(NumberD n1, NumberD n2) - { - try - { - NumberD n12 = Math2Existing.AdaptInputsToMathMethod - ( - n1, Basic.GetSmallIntegers(), ExistingOperations.BigMul - ); - if (!n12.getError().equals(ErrorTypesNumber.None)) - { - return new NumberD(n12.getError()); - } - - NumberD n22 = Math2Existing.AdaptInputsToMathMethod - ( - n2, new ArrayList() - {{ - add(n12.getType()); - }}, - ExistingOperations.BigMul - ); - if (!n22.getError().equals(ErrorTypesNumber.None)) - { - return new NumberD(n22.getError()); - } - - return new NumberD - ( - (long)n12.getValue() * - (long)n22.getValue() - ); - } - catch (Exception e) - { - return new NumberD - ( - ErrorTypesNumber.NativeMethodError - ); - } - } - - /** - NumberD-adapted version of Math.ceil. - @param n Input value. - **/ - public static NumberD Ceiling(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Ceiling - ); - } - - /** - NumberD-adapted version of Math.cos. - @param n Input value. - **/ - public static NumberD Cos(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Cos - ); - } - - /** - NumberD-adapted version of Math.cosh. - @param n Input value. - **/ - public static NumberD Cosh(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Cosh - ); - } - - public static NumberD DivRemOutput = null; - /** - NumberD-adapted version of .NET System.Math.DivRem. - @param n1 Dividend. - @param n2 Divisor. - **/ - public static NumberD DivRem(NumberD n1, NumberD n2) - { - NumberD n12 = Math2Existing.AdaptInputsToMathMethod - ( - n1, Basic.GetSmallIntegers(), ExistingOperations.DivRem - ); - if (!n12.getError().equals(ErrorTypesNumber.None)) - { - DivRemOutput = new NumberD(n12.getError()); - return new NumberD(n12.getError()); - } - - ArrayList tempArray = new ArrayList(); - tempArray.add(n12.getType()); - NumberD n22 = Math2Existing.AdaptInputsToMathMethod - ( - n2, tempArray, ExistingOperations.DivRem - ); - if - ( - !n22.getError().equals(ErrorTypesNumber.None) || - (double)n22.getValue() == 0.0 - ) - { - DivRemOutput = new NumberD(n22.getError()); - return new NumberD(n22.getError()); - } - - n12 = OperationsManaged.PassBaseTenToValue(n12); - n22 = OperationsManaged.PassBaseTenToValue(n22); - - NumberD outNumber = null; - try - { - if (n12.getType().equals(NumericTypes.Long)) - { - long val1 = (long)n12.getValue(); - long val2 = (long)n22.getValue(); - - outNumber = new NumberD(val1 / val2); - DivRemOutput = new NumberD(val1 % val2); - } - else - { - int val1 = (int)n12.getValue(); - int val2 = (int)n22.getValue(); - - outNumber = new NumberD(val1 / val2); - DivRemOutput = new NumberD(val1 % val2); - } - } - catch(Exception e) - { - outNumber = new NumberD(ErrorTypesNumber.NativeMethodError); - DivRemOutput = new NumberD(ErrorTypesNumber.NativeMethodError); - } - - return outNumber; - } - - /** - NumberD-adapted version of Math.exp. - @param n Value to which e will be raised. - **/ - public static NumberD Exp(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Exp - ); - } - - /** - NumberD-adapted version of Math.floor. - @param n Input value. - **/ - public static NumberD Floor(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Floor - ); - } - - /** - NumberD-adapted version of Math.IEEEremainder. - @param n1 Dividend. - @param n2 Divisor. - **/ - public static NumberD IEEERemainder(NumberD n1, NumberD n2) - { - return Math2Existing.PerformOperationTwoOperands - ( - n1, n2, ExistingOperations.IEEERemainder - ); - } - - /** - NumberD-adapted version of Math.log. - @param n Value whose base-n logarithm will be calculated. - **/ - public static NumberD Log(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Log - ); - } - - /** - NumberD-adapted version of .NET System.Math.Log. - @param n1 Value whose logarithm will be calculated. - @param n2 Base of the logarithm. - **/ - public static NumberD Log(NumberD n1, NumberD n2) - { - return Math2Existing.PerformOperationTwoOperands - ( - n1, n2, ExistingOperations.Log - ); - } - - /** - NumberD-adapted version of Math.log10. - @param n Value whose base-10 logarithm will be calculated. - **/ - public static NumberD Log10(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Log10 - ); - } - - /** - NumberD-adapted version of Math.max. - @param n1 First value. - @param n2 Second value. - **/ - public static NumberD Max(NumberD n1, NumberD n2) - { - return Math2Existing.PerformOperationTwoOperands - ( - n1, n2, ExistingOperations.Max - ); - } - - /** - NumberD-adapted version of Math.min. - @param n1 First value. - @param n2 Second value. - **/ - public static NumberD Min(NumberD n1, NumberD n2) - { - return Math2Existing.PerformOperationTwoOperands - ( - n1, n2, ExistingOperations.Min - ); - } - - /** - NumberD-adapted version of Math.pow. - @param n1 Base. - @param n2 Exponent. - **/ - public static NumberD Pow(NumberD n1, NumberD n2) - { - return Math2Existing.PerformOperationTwoOperands - ( - n1, n2, ExistingOperations.Pow - ); - } - - /** - NumberD-adapted version of .NET System.Math.Round. - @param n Input value. - **/ - public static NumberD Round1(NumberD n, MidpointRounding mode) - { - return n; - } - - /** - NumberD-adapted version of .NET System.Math.Round. - @param n Input value. - @param decimals Number of decimal places. - **/ - public static NumberD Round2(NumberD n, int decimals) - { - return Round(n, decimals, MidpointRounding.ToEven); - } - - /** - NumberD-adapted version of .NET System.Math.Round. - @param n Input value. - @param mode Midpoint rounding mode. - **/ - public static NumberD Round3(NumberD n, MidpointRounding mode) - { - return Round(n, 0, mode); - } - - /** - NumberD-adapted version of .NET System.Math.Round. - @param n Input value. - @param decimals Number of decimal places. - @param mode Midpoint rounding mode. - **/ - public static NumberD Round(NumberD n, int decimals, MidpointRounding mode) - { - try - { - NumberD n2 = Math2Existing.AdaptInputsToMathMethod - ( - n, Basic.AllDecimalTypes, ExistingOperations.Round - ); - - return new NumberD - ( - RoundExact - ( - new Number(n2), - decimals, SystemMath.GetNewRoundItemFromExisting - ( - mode - ), - RoundSeparator.AfterDecimalSeparator - ) - ); - } - catch(Exception e) - { - return new NumberD(ErrorTypesNumber.NativeMethodError); - } - } - - /** - NumberD-adapted version of Math.signum. - @param n Input value. - **/ - public static NumberD Sign(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Sign - ); - } - - /** - NumberD-adapted version of Math.sin. - @param n Input value. - **/ - public static NumberD Sin(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Sin - ); - } - - /** - NumberD-adapted version of Math.sinh. - @param n Input value. - **/ - public static NumberD Sinh(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Sinh - ); - } - - /** - NumberD-adapted version of Math.sqrt. - @param n Input value. - **/ - public static NumberD Sqrt(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Sqrt - ); - } - - /** - NumberD-adapted version of Math.tan. - @param n Input value. - **/ - public static NumberD Tan(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Tan - ); - } - - /** - NumberD-adapted version of System.tanh. - @param n Input value. - **/ - public static NumberD Tanh(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Tanh - ); - } - - /** - NumberD-adapted version of .NET System.Math.Truncate. - @param n Input value. - **/ - public static NumberD Truncate(NumberD n) - { - return Math2Existing.PerformOperationOneOperand - ( - n, ExistingOperations.Truncate - ); - } - - //---------------------------- All the public new methods. - - /** - Returns the dependent variable (y), as defined by y = A + B*x + C*x^2. - @param polynomial Coefficients (A, B, C) defining the given polynomial fit. - @param x Independent variable (x). - **/ - public static NumberD ApplyPolynomialFit(Polynomial polynomial, NumberD x) - { - return Math2Regression.ApplyPolynomialFitInternal(polynomial, x); - } - - /** - Determines (least squares) the best polynomial fit for the input x/y sets. - @param x Array containing all the independent variable (x) values. It has to contain the same number of elements than y. - @param y Array containing all the dependent variable (y) values. It has to contain the same number of elements than x. - **/ - public static Polynomial GetPolynomialFit(NumberD[] x, NumberD[] y) - { - return Math2Regression.GetPolynomialFitInternal(x, y); - } - - /** - Calculates the factorial of input value. - @param n Input value. It has to be smaller than 100000. - **/ - public static NumberD Factorial(NumberD n) - { - return Math2Other.FactorialInternal(n); - } - - /** - Calculates the square root of the input value. - It does NOT rely on the custom approach of the original C# version, but on Math.sqrt. - To know about this, read the top comment in InternalNumberParser.Math2Internal.Math2PowSqrt - @param n Input value. - **/ - public static Number SqrtDecimal(Number n) - { - return Math2PowSqrt.PowSqrtInternal(n, 0.5); - } - - /** - Raises the input value to the exponent. - It does NOT rely on the custom approach of the original C# version, but on Math.pow. - To know about this, read the top comment in InternalNumberParser.Math2Internal.Math2PowSqrt - @param n Input value. - @param exponent Exponent. - **/ - public static Number PowDecimal(Number n, double exponent) - { - return Math2PowSqrt.PowSqrtInternal(n, exponent); - } - - /** - Truncates the input value as instructed. - @param n Input value. - **/ - public static Number TruncateExact(Number n) - { - return TruncateExact(n, 0); - } - - /** - Truncates the input value as instructed. - @param n Input value. - @param decimals Number of decimal positions in the result. - **/ - public static Number TruncateExact(Number n, int decimals) - { - return RoundExact - ( - n, decimals, RoundType.AlwaysToZero, - RoundSeparator.AfterDecimalSeparator - ); - } - - /** - Rounds the input value as instructed. - @param n Input value. - **/ - public static Number RoundExact(Number n) - { - return RoundExact(n, 0); - } - - /** - Rounds the input value as instructed. - @param n Input value. - @param digits Number of digits to be considered when rounding. - **/ - public static Number RoundExact(Number n, int digits) - { - return RoundExact - ( - n, digits, RoundType.MidpointToEven, - RoundSeparator.AfterDecimalSeparator - ); - } - - /** - Rounds the input value as instructed. - @param n Input value. - @param type Type of rounding. - **/ - public static Number RoundExact(Number n, RoundType type) - { - return RoundExact - ( - n, 0, type, RoundSeparator.AfterDecimalSeparator - ); - } - - /** - Rounds the input value as instructed. - @param n Input value. - @param digits Number of digits to be considered. - @param type Type of rounding. - **/ - public static Number RoundExact(Number n, int digits, RoundType type) - { - return RoundExact - ( - n, digits, type, RoundSeparator.AfterDecimalSeparator - ); - } - - /** - Rounds the input value as instructed. - @param n Input value. - @param digits Number of digits to be considered. - @param separator Location of the digits to be rounded (before or after the decimal separator). - **/ - public static Number RoundExact(Number n, int digits, RoundSeparator separator) - { - return RoundExact - ( - n, digits, RoundType.MidpointToEven, separator - ); - } - - /** - Rounds the input value as instructed. - @param n Input value. - @param digits Number of digits to be considered. - @param type Type of rounding. - @param separator Location of the digits to be rounded (before or after the decimal separator). - **/ - public static Number RoundExact - ( - Number n, int digits, RoundType type, RoundSeparator separator - ) - { - return Math2RoundTruncate.RoundExactInternal - ( - n, digits, type, separator - ); - } - - /**Decimal version of Math.PI. First 28 decimal digits with no rounding.**/ - public static final double PI = 3.1415926535897932384626433832; - /**Decimal version of Math.E. First 28 decimal digits with no rounding.**/ - public static final double E = 2.7182818284590452353602874713; -} diff --git a/all_code/NumberParser/src_Public/NumberParser/MidpointRounding.java b/all_code/NumberParser/src_Public/NumberParser/MidpointRounding.java deleted file mode 100644 index e819788..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/MidpointRounding.java +++ /dev/null @@ -1,9 +0,0 @@ -package NumberParser; - -/** -Emulation of the in-built .NET enum MidpointRounding which is used in various System.Math.Round overloads. -**/ -public enum MidpointRounding -{ - AwayFromZero, ToEven -} diff --git a/all_code/NumberParser/src_Public/NumberParser/Number.java b/all_code/NumberParser/src_Public/NumberParser/Number.java deleted file mode 100644 index fdc52b5..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/Number.java +++ /dev/null @@ -1,359 +0,0 @@ -package NumberParser; - -import java.util.Locale; - -import InternalNumberParser.*; -import InternalNumberParser.Operations.*; -import InternalNumberParser.OtherParts.*; - -/** -Number is the simplest and lightest NumberX class. -It is implicitly convertible to NumberD, NumberO, NumberP and all the numeric types. -**/ -public class Number implements Comparable -{ - /**Double variable storing the primary value.**/ - private double Value = 0.0; - - /**Value getter.**/ - public double getValue() - { - return Value; - } - - /**Value setter.**/ - public void setValue(double value) - { - Value = value; - if (value == 0) - { - setBaseTenExponent(0); - } - } - - /**Base-ten exponent complementing the primary value.**/ - private int BaseTenExponent = 0; - - /**BaseTenExponent getter.**/ - public int getBaseTenExponent() - { - return BaseTenExponent; - } - - /**BaseTenExponent setter.**/ - public void setBaseTenExponent(int baseTenExponent) - { - BaseTenExponent = baseTenExponent; - } - - /**Error.**/ - private ErrorTypesNumber Error = ErrorTypesNumber.None; - - /**Error getter.**/ - public ErrorTypesNumber getError() - { - return Error; - } - - /**Initialises a new Number instance.**/ - public Number() { } - - /** - Initialises a new Number instance. - @param value Main value to be used. - **/ - public Number(double value) - { - this(value, 0); - } - - /** - Initialises a new Number instance. - @param value Main value to be used. - @param baseTenExponent Base-ten exponent to be used. - **/ - public Number(double value, int baseTenExponent) - { - //To avoid problems with the automatic actions triggered by some setters, it is better - //to always assign values in this order (i.e., first BaseTenExponent and then Value). - setBaseTenExponent(baseTenExponent); - setValue(value); - } - - ErrorTypesNumber PopulateNumberX(Object numberX) - { - Number tempVar = Constructors.ExtractDynamicToNumber(numberX); - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - return tempVar.getError(); - } - - setBaseTenExponent(tempVar.getBaseTenExponent()); - setValue(tempVar.getValue()); - - return ErrorTypesNumber.None; - } - - /** - Initialises a new Number instance. - @param number Number variable whose information will be used. - **/ - public Number(Number number) - { - Error = PopulateNumberX(number); - } - - /** - Initialises a new Number instance. - @param numberD NumberD variable whose information will be used. - **/ - public Number(NumberD numberD) - { - Error = PopulateNumberX(numberD); - } - - /** - Initialises a new Number instance. - @param numberO NumberO variable whose information will be used. - **/ - public Number(NumberO numberO) - { - Error = PopulateNumberX(numberO); - } - - /** - Initialises a new Number instance. - @param numberP NumberP variable whose information will be used. - **/ - public Number(NumberP numberP) - { - Error = PopulateNumberX(numberP); - } - - /** - Initialises a new Number instance. - @param unitP UnitParser's UnitP variable to be used. - **/ - public Number(Object unitP) - { - Number tempVar = OtherPartsUnitParserMethods.GetNumberFromUnitP(unitP); - - Error = PopulateNumberX(tempVar); - } - - //---------------------------- Private Number constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public Number(float value) - { - Number number = Conversions.ConvertAnyValueToDouble(value); - - setValue(number.getValue()); - Error = number.getError(); //float variable can trigger an error (e.g., NaN or infinity). - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public Number(long value) - { - setValue(Conversions.ConvertAnyValueToDouble(value).Value); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public Number(int value) - { - setValue(Conversions.ConvertAnyValueToDouble(value).Value); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public Number(short value) - { - setValue(Conversions.ConvertAnyValueToDouble(value).Value); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public Number(byte value) - { - setValue(Conversions.ConvertAnyValueToDouble(value).Value); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public Number(char value) - { - setValue(Conversions.ConvertAnyValueToDouble(value).Value); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public Number(ErrorTypesNumber error) { Error = error; } - - - //---------------------------- Static methods of Number emulating all the operator overloads of the original C# code. - - /** - Adds two Number variables. - @param first First operand. - @param second Second operand. - @return Number variable resulting from adding first and second. - **/ - public static Number Addition(Number first, Number second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Addition - ); - } - - /** - Subtracts two Number variables. - @param first First operand. - @param second Second operand. - @return Number variable resulting from subtracting first and second. - **/ - public static Number Subtraction(Number first, Number second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Subtraction - ); - } - - /** - Multiplies two Number variables. - @param first First operand. - @param second Second operand. - @return Number variable resulting from multiplying first and second. - **/ - public static Number Multiplication(Number first, Number second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Multiplication - ); - } - - /** - Divides two Number variables. - @param first First operand. - @param second Second operand. - @return Number variable resulting from dividing first and second. - **/ - public static Number Division(Number first, Number second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Division - ); - } - - /** - Calculates the modulo of two Number variables. - @param first First operand. - @param second Second operand. - @return Number variable resulting from calculating the module of first and second. - **/ - public static Number Modulo(Number first, Number second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Modulo - ); - } - - //---------------------------- Non-static and overloaded methods of Number emulating all the comparison overloads in the original C# code. - - /** - Determines whether the current Number instance is greater than other. - @param other Other variable. - **/ - public boolean greaterThan(Number other) - { - return OperationsCompareTo.CompareDouble(this, other) == 1; - } - - /** - Determines whether the current Number instance is greater or equal than other. - @param other Other variable. - **/ - public boolean greaterOrEqualThan(Number other) - { - return OperationsCompareTo.CompareDouble(this, other) >= 0; - } - - /** - Determines whether the current Number instance is smaller than other. - @param other Other variable. - **/ - public boolean lessThan(Number other) - { - return OperationsCompareTo.CompareDouble(this, other) == -1; - } - - /** - Determines whether the current Number instance is smaller or equal than other. - @param other Other variable. - **/ - public boolean lessOrEqualThan(Number other) - { - return OperationsCompareTo.CompareDouble(this, other) <= 0; - } - - @Override - /** - Outputs an error or "Value*10^BaseTenExponent" (BaseTenExponent different than zero sample). - **/ - public String toString() - { - return toString(Locale.US); - } - - /** - Outputs an error or "Value*10^BaseTenExponent" (BaseTenExponent different than zero sample). - @param culture Culture. - **/ - public String toString(Locale culture) - { - if (!Error.equals(ErrorTypesNumber.None)) return "Error. " + Error.toString(); - if (culture == null) culture = Locale.US; - - Number number = OperationsManaged.PassBaseTenToValue(this, true); - return OperationsOther.PrintNumberXInfo - ( - number.getValue(), number.getBaseTenExponent(), null, culture - ); - } - - @Override - /** - Compares the current instance against another Number one. - @param other The other Number instance. - **/ - public int compareTo(Number other) - { - return OperationsCompareTo.CompareDouble(this, other); - } - - @Override - /** - Determines whether the current Number instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals(obj); - } - - boolean Equals(Object other) - { - return - ( - other == null ? false : - OperationsEquals.NumberXsAreEqual - ( - this, (Number)other - ) - ); - } - - @Override - /**Returns the hash code for this Number instance.**/ - public int hashCode() { return 0; } - } diff --git a/all_code/NumberParser/src_Public/NumberParser/NumberD.java b/all_code/NumberParser/src_Public/NumberParser/NumberD.java deleted file mode 100644 index 6c95ee6..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/NumberD.java +++ /dev/null @@ -1,492 +0,0 @@ -package NumberParser; - -import java.util.Locale; - -import InternalNumberParser.*; -import InternalNumberParser.CSharpAdaptation.*; -import InternalNumberParser.Operations.*; -import InternalNumberParser.OtherParts.*; - -/** -NumberD extends the limited decimal-only range of Number by supporting all the numeric types. -It is implicitly convertible to Number, NumberO, NumberP and all the numeric types. -**/ -@SuppressWarnings("rawtypes") -public class NumberD implements Comparable -{ - /**Numeric variable storing the primary value.**/ - private Object Value = 0.0; - - /**Value getter.**/ - public Object getValue() - { - return Value; - } - - /**Value setter.**/ - public void setValue(Object value) - { - NumericTypes type = ErrorInfoNumber.InputTypeIsValidNumeric(value); - - if (type.equals(NumericTypes.None)) - { - setValue(null); - } - else - { - Value = value; - - if - ( - CompareNumeric.BothEqual - ( - Value, Conversions.CastDynamicToType(0, type), type) - ) - { - setBaseTenExponent(0); - } - } - - if (!Type.equals(type)) setType(type); - } - - /**Base-ten exponent complementing the primary value.**/ - private int BaseTenExponent = 0; - - /**BaseTenExponent getter.**/ - public int getBaseTenExponent() - { - return BaseTenExponent; - } - - /**BaseTenExponent setter.**/ - public void setBaseTenExponent(int baseTenExponent) - { - BaseTenExponent = baseTenExponent; - } - - /**Numeric type of the Value property.**/ - private NumericTypes Type = NumericTypes.None; - - /**Type getter.**/ - public NumericTypes getType() - { - return Type; - } - - /**Type setter.**/ - public void setType(NumericTypes type) - { - if (Value != null && !type.equals(NumericTypes.None)) - { - if (NumericTypesMethods.GetTypeFromClass(Value.getClass()).equals(type)) - { - Type = type; - } - else - { - NumberD tempVar = new NumberD - ( - Value, BaseTenExponent, type, false - ); - - if (tempVar.getError().equals(ErrorTypesNumber.None)) - { - Type = type; - setBaseTenExponent(tempVar.getBaseTenExponent()); - setValue(tempVar.getValue()); - } - //else -> The new type is wrong and can be safely ignored. - } - } - } - - /**Readonly member of the ErrorTypesNumber enum which best suits the current conditions.**/ - private ErrorTypesNumber Error = ErrorTypesNumber.None; - - /**Error getter.**/ - public ErrorTypesNumber getError() - { - return Error; - } - - /** - Initialises a new NumberD instance. - @param type Type to be assigned to the dynamic Value property. Only numeric types are valid. - **/ - public NumberD(NumericTypes type) - { - setValue(Basic.GetNumberSpecificType(0, type)); - setType(type); - } - - /** - Initialises a new NumberD instance. - @param value Main value to be used. Only numeric variables are valid. - @param baseTenExponent Base-ten exponent to be used. - **/ - public NumberD(Object value, int baseTenExponent) - { - NumericTypes type = ErrorInfoNumber.InputTypeIsValidNumeric(value); - - if (type == null) - { - Error = ErrorTypesNumber.InvalidInput; - } - else - { - //To avoid problems with the automatic actions triggered by some setters, it is better - //to always assign values in this order (i.e., first BaseTenExponent, then Value and - //finally Type). - setBaseTenExponent(baseTenExponent); - setValue(value); - setType(type); - } - } - - /** - Initialises a new NumberD instance. - @param value Main value to be used. Only numeric variables are valid. - @param type Type to be assigned to the dynamic Value property. Only numeric types are valid. - **/ - public NumberD(Object value, NumericTypes type) - { - NumberD numberD = CSharpOtherNP.ExtractValueAndTypeInfo(value, 0, type); - - if (!numberD.getError().equals(ErrorTypesNumber.None)) - { - Error = numberD.getError(); - } - else - { - setBaseTenExponent(numberD.getBaseTenExponent()); - setValue(numberD.getValue()); - setType(type); - } - } - - /** - Initialises a new NumberD instance. - @param value Main value to be used. Only numeric variables are valid. - @param baseTenExponent Base-ten exponent to be used. - @param type Type to be assigned to the dynamic Value property. Only numeric types are valid. - **/ - public NumberD(Object value, int baseTenExponent, NumericTypes type) - { - NumberD numberD = CSharpOtherNP.ExtractValueAndTypeInfo - ( - value, baseTenExponent, type - ); - - if (!numberD.Error.equals(ErrorTypesNumber.None)) - { - Error = numberD.getError(); - } - else - { - setBaseTenExponent(numberD.getBaseTenExponent()); - setValue(numberD.getValue()); - setType(type); - } - } - - /** - Initialises a new NumberD instance. - @param input Variable whose information will be used. Only NumberD, Number, NumberO, NumberP, numeric and UnitParser's UnitP variables are valid. - **/ - public NumberD(Object input) - { - Class type = ErrorInfoNumber.InputTypeIsValidNumericOrNumberX(input); - - if (type == null) - { - Number number = OtherPartsUnitParserMethods.GetNumberFromUnitP(input); - - if (number.getError().equals(ErrorTypesNumber.None)) - { - setBaseTenExponent(number.getBaseTenExponent()); - setValue(number.getValue()); - setType(NumericTypes.Double); - } - else Error = ErrorTypesNumber.InvalidInput; - } - else - { - if (Basic.AllNumberClassTypes.contains(type)) - { - NumberX.MainVars mainVars = NumberX.GetMainVars(input); - setBaseTenExponent(mainVars.BaseTenExponent); - setValue(mainVars.Value); - - Type = - ( - type.equals(NumberD.class) ? ((NumberD)input).getType() : - NumericTypesMethods.GetTypeFromObject(Value) - ); - Error = mainVars.Error; - } - else - { - setValue(input); - if (Value != null) - { - setType - ( - NumericTypesMethods.GetTypeFromObject(Value) - ); - } - } - } - } - - //---------------------------- Private NumberD constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberD(double value) - { - setValue(value); - setType(NumericTypesMethods.GetTypeFromClass(double.class)); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberD(float value) - { - setValue(value); - setType(NumericTypesMethods.GetTypeFromClass(float.class)); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberD(long value) - { - setValue(value); - setType(NumericTypesMethods.GetTypeFromClass(long.class)); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberD(int value) - { - setValue(value); - setType(NumericTypesMethods.GetTypeFromClass(int.class)); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberD(short value) - { - setValue(value); - setType(NumericTypesMethods.GetTypeFromClass(short.class)); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberD(byte value) - { - setValue(value); - setType(NumericTypesMethods.GetTypeFromClass(byte.class)); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberD(char value) - { - setValue(value); - setType(NumericTypesMethods.GetTypeFromClass(char.class)); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberD() { Error = ErrorTypesNumber.None; } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberD(ErrorTypesNumber error) { Error = error; } - - NumberD(Object value, int baseTenExponent, NumericTypes type, boolean assignType) - { - NumberD numberD = CSharpOtherNP.ExtractValueAndTypeInfo - ( - value, baseTenExponent, type - ); - - if (!numberD.Error.equals(ErrorTypesNumber.None)) - { - Error = numberD.Error; - } - else - { - setBaseTenExponent(numberD.BaseTenExponent); - setValue(numberD.getValue()); - if (assignType) - { - //Condition to avoid an infinite loop when calling this constructor from the Type property setter. - setType(type); - } - } - } - - //---------------------------- Static methods of NumberD emulating all the operator overloads of the original C# code. - - /** - Adds two NumberD variables. - @param first First operand. - @param second Second operand. - @return NumberD variable resulting from adding first and second. - **/ - public static NumberD Addition(NumberD first, NumberD second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Addition - ); - } - - /** - Subtracts two NumberD variables. - @param first First operand. - @param second Second operand. - @return NumberD variable resulting from subtracting first and second. - **/ - public static NumberD Subtraction(NumberD first, NumberD second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Subtraction - ); - } - - /** - Multiplies two NumberD variables. - @param first First operand. - @param second Second operand. - @return NumberD variable resulting from multiplying first and second. - **/ - public static NumberD Multiplication(NumberD first, NumberD second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Multiplication - ); - } - - /** - Divides two NumberD variables. - @param first First operand. - @param second Second operand. - @return NumberD variable resulting from dividing first and second. - **/ - public static NumberD Division(NumberD first, NumberD second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Division - ); - } - - /** - Calculates the modulo of two NumberD variables. - @param first First operand. - @param second Second operand. - @return NumberD variable resulting from calculating the module of first and second. - **/ - public static NumberD Modulo(NumberD first, NumberD second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Modulo - ); - } - - //---------------------------- Non-static and overloaded methods of NumberD emulating all the comparison overloads in the original C# code. - - /** - Determines whether the current NumberD instance is greater than other. - @param other Other variable. - **/ - public boolean greaterThan(NumberD other) - { - return OperationsCompareTo.CompareDouble(this, other) == 1; - } - - /** - Determines whether the current NumberD instance is greater or equal than other. - @param other Other variable. - **/ - public boolean greaterOrEqualThan(NumberD other) - { - return OperationsCompareTo.CompareDouble(this, other) >= 0; - } - - /** - Determines whether the current NumberD instance is smaller than other. - @param other Other variable. - **/ - public boolean lessThan(NumberD other) - { - return OperationsCompareTo.CompareDouble(this, other) == -1; - } - - /** - Determines whether the current NumberD instance is smaller or equal than other. - @param other Other variable. - **/ - public boolean lessOrEqualThan(NumberD other) - { - return OperationsCompareTo.CompareDouble(this, other) <= 0; - } - - @Override - /** - Outputs an error or "Value*10^BaseTenExponent" (BaseTenExponent different than zero sample). - **/ - public String toString() - { - return toString(Locale.US); - } - - /** - Outputs an error or "Value*10^BaseTenExponent" (BaseTenExponent different than zero sample). - @param culture Culture. - **/ - public String toString(Locale culture) - { - if (!Error.equals(ErrorTypesNumber.None)) return "Error. " + Error.toString(); - if (culture == null) culture = Locale.US; - - NumberD numberD = OperationsManaged.PassBaseTenToValue(this, true); - return OperationsOther.PrintNumberXInfo - ( - numberD.getValue(), numberD.getBaseTenExponent(), Type, culture - ); - } - - @Override - /** - Compares the current instance against another NumberD one. - @param other The other NumberD instance. - **/ - public int compareTo(NumberD other) - { - return OperationsCompareTo.CompareDouble(this, other); - } - - @Override - /** - Determines whether the current NumberD instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals(obj); - } - - boolean Equals(Object other) - { - return - ( - other == null ? false : - OperationsEquals.NumberXsAreEqual - ( - this, (NumberD)other - ) - ); - } - - @Override - /**Returns the hash code for this NumberD instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/NumberParser/src_Public/NumberParser/NumberO.java b/all_code/NumberParser/src_Public/NumberParser/NumberO.java deleted file mode 100644 index 4dbd6d7..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/NumberO.java +++ /dev/null @@ -1,617 +0,0 @@ -package NumberParser; - -import java.util.ArrayList; -import java.util.Locale; - -import InternalNumberParser.*; -import InternalNumberParser.Operations.*; -import InternalNumberParser.OtherParts.OtherPartsUnitParserMethods; - -/** -NumberO is the only NumberX class dealing with different numeric types at the same time. -It is implicitly convertible to Number, NumberD, NumberP and all the numeric types. -**/ -public class NumberO implements Comparable -{ - ArrayList _OtherTypes = null; - - private double Value = 0.0; - - /**Value getter.**/ - public double getValue() - { - return Value; - } - - /**Value setter.**/ - public void setValue(double value) - { - Value = value; - - if (Value == 0) BaseTenExponent = 0; - Others = NumberOInternal.PopulateOthers - ( - Value, BaseTenExponent, - NumberOInternal.CheckOtherTypes - ( - _OtherTypes - ) - ); - } - - /**Base-ten exponent complementing the primary value.**/ - private int BaseTenExponent = 0; - - /**BaseTenExponent getter.**/ - public int getBaseTenExponent() - { - return BaseTenExponent; - } - - /**BaseTenExponent setter.**/ - public void setBaseTenExponent(int baseTenExponent) - { - BaseTenExponent = baseTenExponent; - Others = NumberOInternal.PopulateOthers - ( - Value, baseTenExponent, NumberOInternal.CheckOtherTypes - ( - _OtherTypes - ) - ); - } - - /**Collection including all the other numeric types associated with the current conditions.**/ - private ArrayList Others = new ArrayList(); - - /**Others getter.**/ - public final ArrayList getOthers() - { - return Others; - } - - /**Readonly member of the ErrorTypesNumber enum which best suits the current conditions.**/ - private ErrorTypesNumber Error = ErrorTypesNumber.None; - - /**Error getter.**/ - public ErrorTypesNumber getError() - { - return Error; - } - - /**Initialises a new NumberO instance. - public NumberO() { this(0.0); } - - /** - Initialises a new NumberO instance. - @param numberO NumberO variable whose information will be used. - **/ - public NumberO(NumberO numberO) - { - this - ( - numberO, (ArrayList)null - ); - } - - /** - Initialises a new NumberO instance. - @param numberO NumberO variable whose information will be used. - @param otherType Member of the OtherTypes enum determining the types to be considered. - **/ - public NumberO(NumberO numberO, OtherTypes otherType) - { - this - ( - numberO, NumberOInternal.GetAssociatedTypes - ( - otherType - ) - ); - } - - /** - Initialises a new NumberO instance. - @param numberO NumberO variable whose information will be used. - @param otherTypes Collection containing the types to be considered. - **/ - public NumberO(NumberO numberO, ArrayList otherTypes) - { - NumberD tempVar = Constructors.ExtractDynamicToNumberD(numberO); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - //To avoid problems with the automatic actions triggered by some setters, - //it is better to always assign values in this order (i.e., first _OtherTypes/Others, - //then BaseTenExponent and finally Value). - if (otherTypes != null) - { - _OtherTypes = new ArrayList(otherTypes); - } - else - { - Others = new ArrayList - ( - numberO.Others - ); - } - - setBaseTenExponent(tempVar.getBaseTenExponent()); - setValue - ( - Conversions.ConvertTargetToDouble - ( - tempVar.getValue() - ) - ); - } - } - - /** - Initialises a new NumberO instance. - @param number Number variable whose information will be used. - **/ - public NumberO(Number number) - { - NumberD tempVar = Constructors.ExtractDynamicToNumberD(number); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - setBaseTenExponent(tempVar.getBaseTenExponent()); - setValue - ( - Conversions.ConvertTargetToDouble - ( - tempVar.getValue() - ) - ); - } - } - - /** - Initialises a new NumberO instance. - @param numberD NumberD variable whose information will be used. - **/ - public NumberO(NumberD numberD) - { - Number tempVar = Constructors.ExtractDynamicToNumber(numberD); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - setBaseTenExponent(tempVar.getBaseTenExponent()); - setValue(tempVar.getValue()); - } - } - - /** - Initialises a new NumberO instance. - @param numberP NumberP variable whose information will be used. - **/ - public NumberO(NumberP numberP) - { - Number tempVar = Constructors.ExtractDynamicToNumber(numberP); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - setBaseTenExponent(tempVar.getBaseTenExponent()); - setValue(tempVar.getValue()); - } - } - - /** - Initialises a new NumberO instance. - @param value Main value to be used. - @param otherType Member of the OtherTypes enum determining the types to be considered. - **/ - public NumberO(double value, OtherTypes otherType) - { - this - ( - value, 0, otherType, ErrorTypesNumber.None - ); - } - - /** - Initialises a new NumberO instance. - @param value Main value to be used. - @param otherTypes Collection containing the types to be considered. - **/ - public NumberO(double value, ArrayList otherTypes) - { - this - ( - value, 0, otherTypes, ErrorTypesNumber.None - ); - } - - /** - Initialises a new NumberO instance. - @param value Main value to be used. - @param baseTenExponent Base-ten exponent to be used. - @param otherType Member of the OtherTypes enum determining the types to be considered. - **/ - public NumberO(double value, int baseTenExponent, OtherTypes otherType) - { - this - ( - value, baseTenExponent, otherType, ErrorTypesNumber.None - ); - } - - /** - Initialises a new NumberO instance. - @param value Main value to be used. - @param baseTenExponent Base-ten exponent to be used. - @param otherTypes Collection containing the types to be considered. - **/ - public NumberO(double value, int baseTenExponent, ArrayList otherTypes) - { - this - ( - value, baseTenExponent, otherTypes, ErrorTypesNumber.None - ); - } - - /** - Initialises a new NumberO instance. - @param unitP UnitParser's UnitP variable to be used. - **/ - public NumberO(Object unitP) - { - Number tempVar = OtherPartsUnitParserMethods.GetNumberFromUnitP(unitP); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - setBaseTenExponent(tempVar.getBaseTenExponent()); - setValue - ( - Conversions.ConvertTargetToDouble - ( - tempVar.getValue() - ) - ); - } - } - - //---------------------------- Private NumberO constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(double value) - { - Number tempVar = Conversions.ConvertAnyValueToDouble(value); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - //The double type can deliver erroneous values (e.g., NaN or infinity) which are stored as errors. - Error = tempVar.getError(); - } - else - { - //BaseTenExponent needs also to be considered because the double range is bigger than the decimal one. - _OtherTypes = NumberOInternal.GetAssociatedTypes(OtherTypes.AllTypes); - setBaseTenExponent(tempVar.getBaseTenExponent()); - setValue(tempVar.getValue()); - } - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(float value) - { - Number tempVar = Conversions.ConvertAnyValueToDouble(value); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - //The float type can deliver erroneous values (e.g., NaN or infinity) which are stored as errors. - Error = tempVar.getError(); - } - else - { - //BaseTenExponent needs also to be considered because the float range is bigger than the decimal one. - _OtherTypes = NumberOInternal.GetAssociatedTypes(OtherTypes.AllTypes); - setBaseTenExponent(tempVar.getBaseTenExponent()); - setValue(tempVar.getValue()); - } - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(long value) - { - this - ( - Conversions.ConvertAnyValueToDouble(value).getValue(), - 0, OtherTypes.AllTypes, ErrorTypesNumber.None - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(int value) - { - this - ( - Conversions.ConvertAnyValueToDouble(value).getValue(), - 0, OtherTypes.AllTypes, ErrorTypesNumber.None - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(short value) - { - this - ( - Conversions.ConvertAnyValueToDouble(value).getValue(), - 0, OtherTypes.AllTypes, ErrorTypesNumber.None - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(byte value) - { - this - ( - Conversions.ConvertAnyValueToDouble(value).getValue(), - 0, OtherTypes.AllTypes, ErrorTypesNumber.None - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(char value) - { - this - ( - Conversions.ConvertAnyValueToDouble(value).getValue(), - 0, OtherTypes.AllTypes, ErrorTypesNumber.None - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(double value, int baseTenExponent) - { - this - ( - value, baseTenExponent, - OtherTypes.AllTypes, - ErrorTypesNumber.None - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(ErrorTypesNumber error) { Error = error; } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberO(double value, int baseTenExponent, OtherTypes otherType, ErrorTypesNumber error) - { - this - ( - value, baseTenExponent, - NumberOInternal.GetAssociatedTypes - ( - otherType - ), - error - ); - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - NumberO - ( - double value, int baseTenExponent, - ArrayList otherTypes, - ErrorTypesNumber error - ) - { - _OtherTypes = NumberOInternal.CheckOtherTypes - ( - otherTypes - ); - setBaseTenExponent(baseTenExponent); - setValue(value); - Error = error; - } - - - //---------------------------- Static methods of NumberO emulating all the operator overloads of the original C# code. - - /** - Adds two NumberO variables. - @param first First operand. - @param second Second operand. - @return NumberO variable resulting from adding first and second. - **/ - public static NumberO Addition(NumberO first, NumberO second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Addition - ); - } - - /** - Subtracts two NumberO variables. - @param first First operand. - @param second Second operand. - @return NumberO variable resulting from subtracting first and second. - **/ - public static NumberO Subtraction(NumberO first, NumberO second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Subtraction - ); - } - - /** - Multiplies two NumberO variables. - @param first First operand. - @param second Second operand. - @return NumberO variable resulting from multiplying first and second. - **/ - public static NumberO Multiplication(NumberO first, NumberO second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Multiplication - ); - } - - /** - Divides two NumberO variables. - @param first First operand. - @param second Second operand. - @return NumberO variable resulting from dividing first and second. - **/ - public static NumberO Division(NumberO first, NumberO second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Division - ); - } - - /** - Calculates the modulo of two NumberO variables. - @param first First operand. - @param second Second operand. - @return NumberO variable resulting from calculating the module of first and second. - **/ - public static NumberO Modulo(NumberO first, NumberO second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Modulo - ); - } - - //---------------------------- Non-static and overloaded methods of NumberO emulating all the comparison overloads in the original C# code. - - /** - Determines whether the current NumberO instance is greater than other. - @param other Other variable. - **/ - public boolean greaterThan(NumberO other) - { - return OperationsCompareTo.CompareDouble(this, other) == 1; - } - - /** - Determines whether the current NumberO instance is greater or equal than other. - @param other Other variable. - **/ - public boolean greaterOrEqualThan(NumberO other) - { - return OperationsCompareTo.CompareDouble(this, other) >= 0; - } - - /** - Determines whether the current NumberO instance is smaller than other. - @param other Other variable. - **/ - public boolean lessThan(NumberO other) - { - return OperationsCompareTo.CompareDouble(this, other) == -1; - } - - /** - Determines whether the current NumberO instance is smaller or equal than other. - @param other Other variable. - **/ - public boolean lessOrEqualThan(NumberO other) - { - return OperationsCompareTo.CompareDouble(this, other) <= 0; - } - - @Override - /** - Outputs an error or "Value*10^BaseTenExponent" (BaseTenExponent different than zero sample). - **/ - public String toString() - { - return toString(Locale.US); - } - - /** - Outputs an error or "Value*10^BaseTenExponent" (BaseTenExponent different than zero sample). - @param culture Culture. - **/ - public String toString(Locale culture) - { - if (!Error.equals(ErrorTypesNumber.None)) return "Error. " + Error.toString(); - if (culture == null) culture = Locale.US; - - Number number = OperationsManaged.PassBaseTenToValue - ( - new Number(this), true - ); - String output = OperationsOther.PrintNumberXInfo - ( - number.getValue(), number.getBaseTenExponent(), - NumericTypes.Double, culture - ); - - for (NumberD other: Others) - { - output += System.lineSeparator() + OperationsOther.PrintNumberXInfo - ( - other.getValue(), other.getBaseTenExponent(), - other.getType(), culture - ); - } - - return output; - } - - @Override - /** - Compares the current instance against another NumberO one. - @param other The other NumberO instance. - **/ - public int compareTo(NumberO other) - { - return OperationsCompareTo.CompareDouble(this, other); - } - - @Override - /** - Determines whether the current NumberO instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals(obj); - } - - boolean Equals(Object other) - { - return - ( - other == null ? false : - OperationsEquals.NumberXsAreEqual - ( - this, (NumberO)other - ) - ); - } - - @Override - /**Returns the hash code for this NumberO instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/NumberParser/src_Public/NumberParser/NumberP.java b/all_code/NumberParser/src_Public/NumberParser/NumberP.java deleted file mode 100644 index 4443034..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/NumberP.java +++ /dev/null @@ -1,408 +0,0 @@ -package NumberParser; - -import java.util.Locale; - -import InternalNumberParser.*; -import InternalNumberParser.Operations.*; -import InternalNumberParser.OtherParts.OtherPartsUnitParserMethods; - -/** -NumberP is the only NumberX class parsing string inputs. -It is implicitly convertible to Number, NumberD, NumberO and string. -**/ -public class NumberP implements Comparable -{ - /**Readonly primary value under the current conditions.**/ - private Object Value = 0.0; - - /**Value getter.**/ - public Object getValue() - { - return Value; - } - - /**Readonly Base-ten exponent under the current conditions.**/ - private int BaseTenExponent = 0; - - /**BaseTenExponent getter.**/ - public int getBaseTenExponent() - { - return BaseTenExponent; - } - - /**Readonly string variable including the original input to be parsed.**/ - private String OriginalString = null; - - /**OriginalString getter.**/ - public String getOriginalString() - { - return OriginalString; - } - - /**Readonly ParseConfig variable defining the current parsing configuration.**/ - private ParseConfig Config = new ParseConfig(); - - /**ParseConfig getter.**/ - public ParseConfig getParseConfig() - { - return Config; - } - - /**Readonly member of the ErrorTypesNumber enum which best suits the current conditions.**/ - private ErrorTypesNumber Error = ErrorTypesNumber.None; - - /**Error getter.**/ - public ErrorTypesNumber getError() - { - return Error; - } - - /** - Initialises a new NumberP instance. - @param input String variable whose contents will be parsed. - **/ - public NumberP(String input) - { - this - ( - input, new ParseConfig() - ); - } - - /** - Initialises a new NumberP instance. - @param input String variable whose contents will be parsed. - @param config ParseConfig variable whose information will be used. - **/ - public NumberP(String input, ParseConfig config) - { - if (input == null || input.trim().length() < 1) - { - Error = ErrorTypesNumber.InvalidInput; - return; - } - - OriginalString = input; - Config = new ParseConfig(config); - - //NumberD is lighter than NumberP and contains all what matters here (i.e., Object-type Value and BaseTenExponent). - NumberD tempVar = NumberPInternal.StartParse(new ParseInfo(this)); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - BaseTenExponent = tempVar.getBaseTenExponent(); - Value = tempVar.getValue(); - } - } - - /** - Initialises a new NumberP instance. - @param numberP NumberP variable whose information will be used. - **/ - public NumberP(NumberP numberP) - { - if (numberP == null) - { - Error = ErrorTypesNumber.InvalidInput; - } - else - { - BaseTenExponent = numberP.BaseTenExponent; - Value = numberP.Value; - OriginalString = numberP.OriginalString; - Config = new ParseConfig(numberP.Config); - Error = numberP.Error; - } - } - - /** - Initialises a new NumberP instance. - @param number Number variable whose information will be used. - **/ - public NumberP(Number number) - { - Number tempVar = Constructors.ExtractDynamicToNumber(number); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - BaseTenExponent = number.getBaseTenExponent(); - Value = number.getValue(); - Config = new ParseConfig(NumericTypes.Double); - } - } - - /** - Initialises a new NumberP instance. - @param numberD NumberD variable whose information will be used. - **/ - public NumberP(NumberD numberD) - { - NumberD tempVar = Constructors.ExtractDynamicToNumberD(numberD); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - BaseTenExponent = numberD.getBaseTenExponent(); - Value = numberD.getValue(); - Config = new ParseConfig(numberD.getType()); - } - } - - /** - Initialises a new NumberP instance. - @param numberO NumberO variable whose information will be used. - **/ - public NumberP(NumberO numberO) - { - Number tempVar = Constructors.ExtractDynamicToNumber(numberO); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - BaseTenExponent = numberO.getBaseTenExponent(); - Value = numberO.getValue(); - Config = new ParseConfig(NumericTypes.Double); - } - } - - /** - Initialises a new NumberP instance. - @param unitP UnitParser's UnitP variable to be used. - **/ - public NumberP(Object unitP) - { - Number tempVar = OtherPartsUnitParserMethods.GetNumberFromUnitP(unitP); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - BaseTenExponent = tempVar.getBaseTenExponent(); - Value = tempVar.getValue(); - Config = new ParseConfig(NumericTypes.Double); - } - } - - //---------------------------- Private NumberP constructors. - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberP(Number number, String originalString, ParseConfig config) - { - Number tempVar = Constructors.ExtractDynamicToNumber(number); - - if (!tempVar.getError().equals(ErrorTypesNumber.None)) - { - Error = tempVar.getError(); - } - else - { - BaseTenExponent = number.getBaseTenExponent(); - Value = number.getValue(); - OriginalString = originalString; - Config = new ParseConfig(config); - } - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberP(Object value, int baseTenExponent) - { - BaseTenExponent = baseTenExponent; - Value = value; - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public NumberP(ErrorTypesNumber error) { Error = error; } - - - //---------------------------- Static methods of NumberP emulating all the operator overloads of the original C# code. - - /** - Adds two NumberP variables. - @param first First operand. - @param second Second operand. - @return NumberP variable resulting from adding first and second. - **/ - public static NumberP Addition(NumberP first, NumberP second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Addition - ); - } - - /** - Subtracts two NumberO variables. - @param first First operand. - @param second Second operand. - @return NumberP variable resulting from subtracting first and second. - **/ - public static NumberP Subtraction(NumberP first, NumberP second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Subtraction - ); - } - - /** - Multiplies two NumberP variables. - @param first First operand. - @param second Second operand. - @return NumberP variable resulting from multiplying first and second. - **/ - public static NumberP Multiplication(NumberP first, NumberP second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Multiplication - ); - } - - /** - Divides two NumberP variables. - @param first First operand. - @param second Second operand. - @return NumberP variable resulting from dividing first and second. - **/ - public static NumberP Division(NumberP first, NumberP second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Division - ); - } - - /** - Calculates the modulo of two NumberP variables. - @param first First operand. - @param second Second operand. - @return NumberP variable resulting from calculating the module of first and second. - **/ - public static NumberP Modulo(NumberP first, NumberP second) - { - return OperationsManaged.PerformArithmeticOperation - ( - first, second, ExistingOperations.Modulo - ); - } - - //---------------------------- Non-static and overloaded methods of NumberP emulating all the comparison overloads in the original C# code. - - /** - Determines whether the current NumberP instance is greater than other. - @param other Other variable. - **/ - public boolean greaterThan(NumberP other) - { - return OperationsCompareTo.CompareDouble(this, other) == 1; - } - - /** - Determines whether the current NumberP instance is greater or equal than other. - @param other Other variable. - **/ - public boolean greaterOrEqualThan(NumberP other) - { - return OperationsCompareTo.CompareDouble(this, other) >= 0; - } - - /** - Determines whether the current NumberP instance is smaller than other. - @param other Other variable. - **/ - public boolean lessThan(NumberP other) - { - return OperationsCompareTo.CompareDouble(this, other) == -1; - } - - /** - Determines whether the current NumberP instance is smaller or equal than other. - @param other Other variable. - **/ - public boolean lessOrEqualThan(NumberP other) - { - return OperationsCompareTo.CompareDouble(this, other) <= 0; - } - - @Override - /** - Outputs an error or "Value*10^BaseTenExponent" (BaseTenExponent different than zero sample). - **/ - public String toString() - { - return toString(Locale.US); - } - - /** - Outputs an error or "Value*10^BaseTenExponent" (BaseTenExponent different than zero sample). - @param culture Culture. - **/ - public String toString(Locale culture) - { - if (!Error.equals(ErrorTypesNumber.None)) return "Error. " + Error.toString(); - if (culture == null) culture = Locale.US; - - NumberD numberD = OperationsManaged.PassBaseTenToValue - ( - new NumberD(this), true - ); - - return OperationsOther.PrintNumberXInfo - ( - numberD.getValue(), numberD.getBaseTenExponent(), null, culture - ) - + " (" + OriginalString + ")" + System.lineSeparator() + Config.toString(); - } - - @Override - /** - Compares the current instance against another NumberP one. - @param other The other NumberP instance. - **/ - public int compareTo(NumberP other) - { - return OperationsCompareTo.CompareDouble(this, other); - } - - @Override - /** - Determines whether the current NumberP instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals(obj); - } - - boolean Equals(Object other) - { - return - ( - other == null ? false : - OperationsEquals.NumberXsAreEqual - ( - this, (NumberP)other - ) - ); - } - - @Override - /**Returns the hash code for this NumberO instance.**/ - public int hashCode() { return 0; } -} \ No newline at end of file diff --git a/all_code/NumberParser/src_Public/NumberParser/NumericTypes.java b/all_code/NumberParser/src_Public/NumberParser/NumericTypes.java deleted file mode 100644 index be056ba..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/NumericTypes.java +++ /dev/null @@ -1,22 +0,0 @@ -package NumberParser; - -/**Enum aiming to simplify the in-built Java recognition of numeric types/classes.**/ -public enum NumericTypes -{ - /**No type.**/ - None, - /**Double or double.**/ - Double, - /**Float or float.**/ - Float, - /**Long or long.**/ - Long, - /**Integer or int.**/ - Integer, - /**Short or short.**/ - Short, - /**Byte or byte.**/ - Byte, - /**Character or char.**/ - Character -} \ No newline at end of file diff --git a/all_code/NumberParser/src_Public/NumberParser/NumericTypesMethods.java b/all_code/NumberParser/src_Public/NumberParser/NumericTypesMethods.java deleted file mode 100644 index 17a1492..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/NumericTypesMethods.java +++ /dev/null @@ -1,62 +0,0 @@ -package NumberParser; - -/**Class including all the methods performing the main actions associated with the NumericTypes enum.**/ -@SuppressWarnings("rawtypes") -public class NumericTypesMethods -{ - /** - Determines NumericTypes item matching the given variable. - @param input Numeric variable whose type will be determined. - @return Item of the NumericTypes enum best matching the input variable. - **/ - public static NumericTypes GetTypeFromObject(Object input) - { - return - ( - input == null ? NumericTypes.None : - GetTypeFromClass(input.getClass()) - ); - } - - /** - Determines the NumericTypes item matching the given class. - @param input Class whose type will be determined. - @return Item of the NumericTypes enum best matching the input class. - **/ - public static NumericTypes GetTypeFromClass(Class input) - { - NumericTypes output = NumericTypes.None; - if (input == null) return output; - - if (input.equals(double.class) || input.equals(Double.class)) - { - output = NumericTypes.Double; - } - else if (input.equals(float.class) || input.equals(Float.class)) - { - output = NumericTypes.Float; - } - else if (input.equals(long.class) || input.equals(Long.class)) - { - output = NumericTypes.Long; - } - else if (input.equals(int.class) || input.equals(Integer.class)) - { - output = NumericTypes.Integer; - } - else if (input.equals(short.class) || input.equals(Short.class)) - { - output = NumericTypes.Short; - } - else if (input.equals(byte.class) || input.equals(Byte.class)) - { - output = NumericTypes.Byte; - } - else if (input.equals(char.class) || input.equals(Character.class)) - { - output = NumericTypes.Character; - } - - return output; - } -} \ No newline at end of file diff --git a/all_code/NumberParser/src_Public/NumberParser/OtherTypes.java b/all_code/NumberParser/src_Public/NumberParser/OtherTypes.java deleted file mode 100644 index 6944068..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/OtherTypes.java +++ /dev/null @@ -1,21 +0,0 @@ -package NumberParser; - -/**Determines the group of numeric types to be considered at NumberO instantiation.**/ -public enum OtherTypes -{ - /**No types.**/ - None, - /**All the numeric types.**/ - AllTypes, - /**Only the following types: decimal, double, long and int.**/ - MostCommonTypes, - /**Only the following types: long, ulong, int, uint, short, ushort, char, sbyte and byte.**/ - IntegerTypes, - /**Only the following types: decimal, double and float.**/ - DecimalTypes, - /**Only the following types: decimal, double, float, long, ulong, int and uint.**/ - BigTypes, - /**Only the following types: short, ushort, sbyte, byte and char.**/ - SmallTypes -} - diff --git a/all_code/NumberParser/src_Public/NumberParser/ParseConfig.java b/all_code/NumberParser/src_Public/NumberParser/ParseConfig.java deleted file mode 100644 index 3bf73b1..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/ParseConfig.java +++ /dev/null @@ -1,137 +0,0 @@ -package NumberParser; - -import java.util.Locale; - -import InternalNumberParser.Operations.*; - -/**ParseConfig defines the way in which the ParseConfig parsing actions are being performed.**/ -public class ParseConfig -{ - /**Locale variable to be used while parsing. Its default value is Locale.getDefault().**/ - private Locale Culture = Locale.getDefault(); - - /**Culture getter.**/ - public Locale getCulture() - { - return Culture; - } - - /**Culture setter.**/ - public void setCulture(Locale culture) - { - Culture = culture; - } - - /**Member of the ParseTypes enum defining the parsing type. Its default value is ParseTypes.ParseAll.**/ - private ParseTypes ParseType = ParseTypes.ParseAll; - - /**ParseType getter.**/ - public ParseTypes getParseType() - { - return ParseType; - } - - /**ParseType setter.**/ - public void setParseType(ParseTypes parseType) - { - ParseType = parseType; - } - - /**Numeric type targeted by the parsing actions. Its default value is NumericTypes.Double.**/ - private NumericTypes Target = NumericTypes.Double; - - /**Target getter.**/ - public NumericTypes getTarget() - { - return Target; - } - - /**Target setter.**/ - public void setTarget(NumericTypes target) - { - Target = target; - } - - /**Initialises a new ParseConfig instance.**/ - public ParseConfig() { } - - /** - Initialises a new ParseConfig instance. - @param target Type variable defining the numeric type targeted by the parsing actions. - **/ - public ParseConfig(NumericTypes target) - { - Target = - ( - target.equals(NumericTypes.None) ? - NumericTypes.Double : target - ); - } - - /** - Initialises a new ParseConfig instance. - @param config ParseConfig variable whose information will be used. - **/ - public ParseConfig(ParseConfig config) - { - if (config == null) - { - config = new ParseConfig(); - Culture = config.Culture; - ParseType = config.ParseType; - Target = config.Target; - - return; - } - - Culture = - ( - config.Culture != null ? - config.Culture : Locale.getDefault() - ); - - ParseType = config.ParseType; - Target = - ( - !config.Target.equals(NumericTypes.None) ? - config.Target : NumericTypes.Double - ); - } - - @Override - /** - Outputs the information in all the public fields (one per line). - **/ - public String toString() - { - String output = "Culture: " + Culture.getDisplayName() + System.lineSeparator(); - - output += "ParseType: " + ParseType.toString() + System.lineSeparator(); - output += "Target: " + (Target != null ? Target.toString() : "nothing"); - - return output; - } - - @Override - /** - Determines whether the current ParseConfig instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((ParseConfig)obj); - } - - boolean Equals(ParseConfig other) - { - return - ( - other == null ? false : - OperationsEquals.ParseConfigsAreEqual(this, other) - ); - } - - @Override - /**Returns the hash code for this ParseConfig instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/NumberParser/src_Public/NumberParser/ParseTypes.java b/all_code/NumberParser/src_Public/NumberParser/ParseTypes.java deleted file mode 100644 index e98eddb..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/ParseTypes.java +++ /dev/null @@ -1,20 +0,0 @@ -package NumberParser; - -/**Determines the main rules to be applied when parsing the string input at NumberP instantiation.**/ -public enum ParseTypes -{ - /**All the strings are parsed without any restriction.**/ - ParseAll, - /**Only strings which fit within the range of the target type are acceptable.**/ - ParseOnlyTarget, - /** - Invalid thousands separators trigger an error. Any valid configuration, supported by the given culture or not, is acceptable. - Supported configurations for thousands separators: standard (groups of 3), Indian (first group of 3 and then groups of 2) and Chinese (groups of 4). Additionally to the group separators for the given culture, blank spaces are also supported. - **/ - ParseThousandsStrict, - /** - Only strings which fit within the range of the target type and include valid thousands separators (any configuration) are acceptable. - Supported configurations for thousands separators: standard (groups of 3), Indian (first group of 3 and then groups of 2) and Chinese (groups of 4). Additionally to the group separators for the given culture, blank spaces are also supported. - **/ - ParseOnlyTargetAndThousandsStrict -} diff --git a/all_code/NumberParser/src_Public/NumberParser/Polynomial.java b/all_code/NumberParser/src_Public/NumberParser/Polynomial.java deleted file mode 100644 index 16588a2..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/Polynomial.java +++ /dev/null @@ -1,163 +0,0 @@ -package NumberParser; - -import java.util.Locale; - -import InternalNumberParser.Operations.*; - -/** -Stores the coefficients defining a second degree polynomial fit via y = A + B*x + C*x^2. -**/ -public class Polynomial -{ - /** - Compares the current instance against another Polynomial one. - @param other The other Polynomial instance. - **/ - public int CompareTo(Polynomial other) - { - if (this.A != other.A) - { - return OperationsCompareTo.CompareDynamic(this.A, other.A); - } - if (this.B != other.B) - { - return OperationsCompareTo.CompareDynamic(this.B, other.B); - } - - return OperationsCompareTo.CompareDynamic(this.C, other.C); - } - - /**Polynomial coefficient A, as defined by y = A + B*x + C*x^2.**/ - public NumberD A = null; - - /**Coefficient A getter.**/ - public NumberD getCoefficientA() - { - return A; - } - - /**Coefficient A setter.**/ - public void setCoefficientA(NumberD a) - { - A = new NumberD(a); - } - /**Polynomial coefficient B, as defined by y = A + B*x + C*x^2.**/ - public NumberD B = null; - - /**Coefficient B getter.**/ - public NumberD getCoefficientB() - { - return B; - } - - /**Coefficient B setter.**/ - public void setCoefficientB(NumberD b) - { - B = new NumberD(b); - } - - /**Polynomial coefficient C, as defined by y = A + B*x + C*x^2.**/ - public NumberD C = null; - - /**Coefficient C getter.**/ - public NumberD getCoefficientC() - { - return C; - } - - /**Coefficient C setter.**/ - public void setCoefficientC(NumberD c) - { - C = new NumberD(c); - } - - public ErrorTypesNumber Error = ErrorTypesNumber.None; - - /**Error getter.**/ - public ErrorTypesNumber getError() - { - return Error; - } - - /** - Initialises a new Polynomial instance. - @param a Coefficient A in y = A + B*x + C*x^2. - @param b Coefficient B in y = A + B*x + C*x^2. - @param c Coefficient C in y = A + B*x + C*x^2. - **/ - public Polynomial(NumberD a, NumberD b, NumberD c) - { - A = new NumberD(a); - B = new NumberD(b); - C = new NumberD(c); - - if - ( - !A.getError().equals(ErrorTypesNumber.None) || - !B.getError().equals(ErrorTypesNumber.None) || - !C.getError().equals(ErrorTypesNumber.None) - ) - { - A = null; - B = null; - C = null; - - Error = ErrorTypesNumber.InvalidInput; - } - } - - /** WARNING: the purpose of this constructor in the original C# code was to be exclusively used internally. */ - public Polynomial(ErrorTypesNumber error) { Error = error; } - - @Override - /** - Outputs the information in all the public fields (one per line). - **/ - public String toString() - { - return toString(Locale.US); - } - - /** - Outputs the information in all the public fields (one per line). - **/ - public String toString(Locale culture) - { - if (!Error.equals(ErrorTypesNumber.None)) return "Error. " + Error.toString(); - if (culture == null) culture = Locale.getDefault(); - - return - ( - A == null || B == null || C == null ? "" : - "A: " + A.toString(culture) + System.lineSeparator() + - "B: " + B.toString(culture) + System.lineSeparator() + - "C: " + C.toString(culture) - ); - } - - @Override - /** - Determines whether the current Polynomial instance is equal to other one. - @param obj Other variable. - **/ - public boolean equals(Object obj) - { - return Equals((Polynomial)obj); - } - - boolean Equals(Polynomial other) - { - return - ( - other == null ? false : - OperationsEquals.PolynomialsAreEqual - ( - this, other - ) - ); - } - - @Override - /**Returns the hash code for this Polynomial instance.**/ - public int hashCode() { return 0; } -} diff --git a/all_code/NumberParser/src_Public/NumberParser/RoundSeparator.java b/all_code/NumberParser/src_Public/NumberParser/RoundSeparator.java deleted file mode 100644 index a92f011..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/RoundSeparator.java +++ /dev/null @@ -1,12 +0,0 @@ -package NumberParser; - -/** -Indicates the location of the digits being rounded (i.e., before or after the decimal separator). -**/ -public enum RoundSeparator -{ - /**Only the digits after the decimal separator are rounded.**/ - AfterDecimalSeparator, - /**Only the digits before the decimal separator are rounded. The digits after the decimal separator might also be analysed (e.g., midpoint determination).**/ - BeforeDecimalSeparator -} diff --git a/all_code/NumberParser/src_Public/NumberParser/RoundType.java b/all_code/NumberParser/src_Public/NumberParser/RoundType.java deleted file mode 100644 index 1980958..0000000 --- a/all_code/NumberParser/src_Public/NumberParser/RoundType.java +++ /dev/null @@ -1,20 +0,0 @@ -package NumberParser; - -/** -Indicates the type of rounding, as defined by the way in which the last digit is being rounded. -**/ -public enum RoundType -{ - /**When a number is halfway between two others, it is rounded to the number which is further from zero.**/ - MidpointAwayFromZero, - /**When a number is halfway between two others, it is rounded to the number which is even.**/ - MidpointToEven, - /**When a number is halfway between two others, it is rounded to the number which is closer to zero.**/ - MidpointToZero, - /**A number is always rounded to the number which is further from zero.**/ - AlwaysToEven, - /**A number is always rounded to the number which is closer to zero.**/ - AlwaysAwayFromZero, - /**A number is always rounded to the even number.**/ - AlwaysToZero -} diff --git a/all_code/Test/.classpath b/all_code/Test/.classpath deleted file mode 100644 index 8384cc9..0000000 --- a/all_code/Test/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/all_code/Test/.project b/all_code/Test/.project deleted file mode 100644 index c6f81a5..0000000 --- a/all_code/Test/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - Test - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/all_code/Test/.settings/org.eclipse.core.resources.prefs b/all_code/Test/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 8b4606f..0000000 --- a/all_code/Test/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/Parts/UnitParser.java=UTF-8 diff --git a/all_code/Test/NumberParser.jar b/all_code/Test/NumberParser.jar deleted file mode 100644 index ee95ed8..0000000 Binary files a/all_code/Test/NumberParser.jar and /dev/null differ diff --git a/all_code/Test/UnitParser.jar b/all_code/Test/UnitParser.jar deleted file mode 100644 index eba6d5f..0000000 Binary files a/all_code/Test/UnitParser.jar and /dev/null differ diff --git a/all_code/Test/build.xml b/all_code/Test/build.xml deleted file mode 100644 index 91ca4a1..0000000 --- a/all_code/Test/build.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/all_code/Test/src/Main.java b/all_code/Test/src/Main.java deleted file mode 100644 index 5a3ed29..0000000 --- a/all_code/Test/src/Main.java +++ /dev/null @@ -1,13 +0,0 @@ -import Parts.*; - -public class Main -{ - public static void main(String[] args) - { - //UnitParser tests. - //UnitParser.StartTest(); - - //NumberParser tests. - NumberParser.StartTest(); - } -} \ No newline at end of file diff --git a/all_code/Test/src/Parts/NumberParser.java b/all_code/Test/src/Parts/NumberParser.java deleted file mode 100644 index 9e3b38a..0000000 --- a/all_code/Test/src/Parts/NumberParser.java +++ /dev/null @@ -1,182 +0,0 @@ -package Parts; - -import java.util.ArrayList; - -import NumberParser.*; -import NumberParser.Number; -import UnitParser.*; -import InternalNumberParser.CSharpAdaptation.*; - -@SuppressWarnings("serial") -public class NumberParser -{ - public static void main(String[] args) - { - StartTest(); - } - - public static void StartTest() - { - System.out.println("-------------- NumberParser --------------"); - System.out.println(); - - //------ There are 4 main classes (NumberX) which take care of different actions. - - //--- Number is the simplest and lightest one. - PrintSampleItem("Ini1", new Number(123.45678945699)); - PrintSampleItem("Ini2", new Number(Double.MAX_VALUE, Integer.MAX_VALUE)); - - //--- NumberD is the simplest version supporting any numeric type. - PrintSampleItem("Ini3", new NumberD(1.5634456f)); - PrintSampleItem("Ini4", new NumberD(555555555555555555l, NumericTypes.Long)); - - //--- NumberO can deal with different numeric types at the same time. - PrintSampleItem("Ini5", new NumberO(1567894563321.5634456, OtherTypes.IntegerTypes)); - ArrayList others = new ArrayList() - {{ - add(NumericTypes.Short); - add(NumericTypes.Double); - }}; - - PrintSampleItem - ( - "Ini6", new NumberO - ( - new NumberO(new NumberD(53264485)), others - ) - ); - - //--- NumberP is the only one extracting numeric information from strings. - PrintSampleItem("Ini7", new NumberP("12555555.2", new ParseConfig(NumericTypes.Byte))); - PrintSampleItem - ( - "Ini8", new NumberP - ( - "1 00 00 000", new ParseConfig() - {{ - setParseType(ParseTypes.ParseThousandsStrict); - }} - ) - ); - - //------ All the NumberX classes support the most common operations. - - //--- Arithmetic operators. - PrintSampleItem("Op1", Number.Addition(new Number(1.233333658789), new Number(0.0000000012))); - PrintSampleItem - ( - "Op2", Number.Division - ( - Number.Multiplication - ( - new Number(1000.0), new Number(new NumberD(55555555555555555555.55555)) - ), - new Number(new NumberP("1e-350")) - ) - ); - - //--- Comparison operators. - PrintSampleItem - ( - "Op3", - ( - new Number(555.0, -3).equals - ( - new Number(new NumberP("0.555")) - ) - ? new Number(1.0) : new Number() - ) - ); - PrintSampleItem - ( - "Op4", - ( - new Number(123.5).lessOrEqualThan - ( - new Number(new NumberD(123)) - ) - ? new Number(1.0) : new Number() - ) - ); - - //------ Math2 contains NumberX-adapted versions of all the .NET System.Math methods. - - //--- The expectations of the corresponding native method have to be met, otherwise an error would be triggered. - PrintSampleItem("Math1", Math2.Max(new NumberD(999), new NumberD(1.234))); //Valid scenario for Math.Max (int implicitly convertible to double). - PrintSampleItem("Math2", Math2.Pow(new NumberD(5555555555l, 500), new NumberD(5.3))); //Error. 5555555555*10^500 is outside the Math.Pow supported range. - - //--- If the target range is met, using the expected format isn't always required. - PrintSampleItem("Math3", Math2.Log(new NumberD(20, 3))); //No error despite calling Math.Log with decimal when it expects double. - PrintSampleItem("Math4", Math2.Sin(new NumberD('e'))); //No error despite calling Math.Sin with char when it expects double. - - - //------ Math2 also includes other mathematical methods which I developed completely from scratch. - - //--- The PowDecimal/SqrtDecimal algorithms only rely on the decimal type and are more precise than the native versions. - //--- You can find more information about these algorithms in https://varocarbas.com/fractional_exponentiation/. - PrintSampleItem("Math5", Math2.PowDecimal(new Number(0.0000000000000001), 1.234567895)); - PrintSampleItem("Math6", Math2.SqrtDecimal(new Number(9999999999999999999.0, 500))); - - //-- RoundExact/TruncateExact can deal with multiple rounding/truncating scenarios which aren't supported by the native methods. - PrintSampleItem - ( - "Math7", Math2.RoundExact - ( - new Number(124555897.5500008), 4, RoundType.AlwaysToEven, - RoundSeparator.BeforeDecimalSeparator - ) - ); - PrintSampleItem("Math8", Math2.TruncateExact(new Number(5.123999), 3)); - - //-- GetPolynomialFit/ApplyPolynomialFit allow to perform regression analysis (2nd degree polynomial fits created via least squares). - PrintSampleItem - ( - "Math9", Math2.ApplyPolynomialFit - ( - Math2.GetPolynomialFit - ( - new NumberD[] { new NumberD(1), new NumberD(2), new NumberD(4) }, - new NumberD[] { new NumberD(1), new NumberD(4), new NumberD(16) } - ), - new NumberD(3) - ) - ); - - //-- Factorial calculates the factorial of any integer number up to 100000. - PrintSampleItem("Math10", Math2.Factorial(new NumberD(25))); - - - //------ Other FlexibleParser parts. - //All the FlexibleParser parts are independent among each other and only the corresponding DLL file needs to be referred. - //On the other, codes relying on various parts can take advantage of certain compatibility among their main classes. - - //--- UnitParser. - PrintSampleItem("UP1", new Number(new UnitP("12.3 MabA"))); - PrintSampleItem("UP2", new NumberD(new UnitP(0.01, SIPrefixes.Micro.toString() + Units.Second.toString()))); - PrintSampleItem("UP3", new NumberP(new UnitP("Error"))); - - - System.out.println(); - System.out.println("------------------------------------------"); - System.out.println(); - System.out.println(); - } - - static void PrintSampleItem(String sampleId, Object numberX) - { - System.out.println - ( - sampleId + " -- " + - ( - numberX == null ? " " : - numberX.getClass().getName().replace - ( - "NumberParser.", "" - ) - ) - //Each ToString() method outputs what the given NumberX needs. - + " - " + CSharpOtherNP.SpecificNumberXToString(numberX) - + System.lineSeparator() - ); - } -} diff --git a/all_code/UnitParser/.settings/org.eclipse.jdt.core.prefs b/all_code/UnitParser/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index a698e59..0000000 --- a/all_code/UnitParser/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,12 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/all_code/UnitParser/.settings/org.eclipse.ltk.core.refactoring.prefs b/all_code/UnitParser/.settings/org.eclipse.ltk.core.refactoring.prefs deleted file mode 100644 index b196c64..0000000 --- a/all_code/UnitParser/.settings/org.eclipse.ltk.core.refactoring.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false diff --git a/all_comments/NumberParser.doc.zip b/all_comments/NumberParser.doc.zip deleted file mode 100644 index 4651197..0000000 Binary files a/all_comments/NumberParser.doc.zip and /dev/null differ diff --git a/all_readme/UnitParser_Java.md b/all_readme/UnitParser_Java.md deleted file mode 100644 index 1fecc57..0000000 --- a/all_readme/UnitParser_Java.md +++ /dev/null @@ -1,136 +0,0 @@ -# UnitParser (Java) - -[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.807522.svg)](https://zenodo.org/record/807522) - -[Last release](https://github.com/varocarbas/FlexibleParser_Java/releases/tag/UnitParser_1.0.9.0) -- [Test program](https://github.com/varocarbas/FlexibleParser_Java/blob/master/all_code/Test/src/Parts/UnitParser.java) - -[https://customsolvers.com/unit_parser_java/](https://customsolvers.com/unit_parser_java/) (ES: [https://customsolvers.com/unit_parser_java_es/](https://customsolvers.com/unit_parser_java_es/)) - -## Introduction -The main class is called ```UnitP``` (```UnitParser``` package). It can be instantiated in many different ways. - -```Java -//1 N. -UnitP unitP = new UnitP("1 N"); - -//1 N. -unitP = new UnitP(1.0, UnitSymbols.Newton); - -//1 N. -unitP = new UnitP(1.0, "nEwTon"); - -//1 N. -unitP = new UnitP(1.0, Units.Newton); -``` - -```UnitP``` can be seen as an abstract concept including many specific types ([full list](https://github.com/varocarbas/FlexibleParser_Java/blob/master/all_code/UnitParser/src_Public/UnitParser/UnitTypes.java)). Same-type variables can be added/subtracted. Different-type variables can be multiplied/divided, but only in case of generating a valid-type output. - -```Java -//2 N. -unitP = UnitP.Addition(new UnitP("1 N"), new UnitP(1.0, Units.Newton)); - -//1 J. -unitP = UnitP.Multiplication(new UnitP("1 N"), new UnitP("1 m")); - -//Error not triggering an exception. -//The output unit N*m^2 doesn't match any supported type. -unitP = UnitP.Multiplication -( - UnitP.Multiplication - ( - new UnitP("1 N"), new UnitP("1 m") - ), - new UnitP("1 m") -); -``` - -### Main Variable Information -```UnitP``` variables are defined according to various ```final``` fields populated at instantiation. - -```Unit``` - Corresponding [Units](https://github.com/varocarbas/FlexibleParser_Java/blob/master/all_code/UnitParser/src_Public/UnitParser/Units.java) member.
-```UnitType``` - Corresponding [UnitTypes](https://github.com/varocarbas/FlexibleParser_Java/blob/master/all_code/UnitParser/src_Public/UnitParser/UnitTypes.java) member.
-```UnitSystem``` - Corresponding [UnitSystems](https://github.com/varocarbas/FlexibleParser_Java/blob/master/all_code/UnitParser/src_Public/UnitParser/UnitSystems.java) member.
-```UnitParts``` - Defining parts of the given unit.
-```UnitPrefix``` - [Supported prefix](https://github.com/varocarbas/FlexibleParser_Java/blob/master/all_code/UnitParser/src_Public/UnitParser/Prefix.java) affecting all the unit parts.
-```BaseTenExponent``` - Base-ten exponent used when dealing with too small/big values.
-```Error``` - Variable storing all the error- and exception-related information. - -## General Rules - -All the functionalities are based upon the following ideas: -- In case of incompatibility, the first element is always preferred. -- By default, the formally-correct alternative is preferred. Some required modifications might be performed. -- By default, all the errors are managed internally. - -```Java -//1.3048. -unitP = UnitP.Addition(new UnitP("1 m"), new UnitP("1 ft")); - -//Error not triggering an exception. -//The parser expects "km" or a full-name-based version like "KiLom". -unitP = new UnitP("1 Km"); - -//999999.9999999001*10^19 YSt. -unitP = UnitP.Multiplication -( - 999999999999999999999999999999999999.9, - new UnitP("9999999999999 St") -); -``` - -## Unit String Parsing Format - -The unit string parsing part is quite flexible, but there are some basic rules. -- String multi-part units are expected to be exclusively formed by units, multiplication/division signs and integer exponents. -- Only one division sign is expected. The parser understands that all what lies before/after it is the numerator/denominator. - -```Java -//1 W. -unitP = new UnitP("1 J*J/s*J2*J-1*s*s-1"); - -//Error not triggering an exception. -//The parser understands "J*J/(s*J2*s*J*s)", what doesn't represent a supported type. -unitP = new UnitP("1 J*J/(s*J2*s)*J*s"); -``` - -## Numeric Support -Formally, only the ```double``` type is supported. Practically, ```UnitP``` variables implement a mixed system delivering beyond-```double```-range support. - -```Java -//7.891011 ft. -unitP = UnitP.Multiplication(new UnitP("1 ft"), 7.891011); - -//1.213141516 Gs. -unitP = UnitP.Multiplication(new UnitP("1 s"), 1213141516.0); - -//0.0003094346047382587*10^-752 ym. -unitP = UnitP.Division -( - UnitP.Division - ( - UnitP.Division - ( - UnitP.Multiplication - ( - 0.0000000000000000000000000000000000000000000000001, - new UnitP(0.000000000000000000001, "ym2") - ), - new UnitP("999999999999999999999 Ym") - ), - Double.MAX_VALUE - ), - Double.MAX_VALUE -); -``` - -## Further Code Samples -The [test application](https://github.com/varocarbas/FlexibleParser_Java/blob/master/all_code/Test/src/Parts/UnitParser.java) includes a relevant number of descriptive code samples. - -## Authorship & Copyright - -I, Alvaro Carballo Garcia (varocarbas), am the sole author of each single bit of this code. - -Equivalently to what happens with all my other online contributions, this code can be considered public domain. For more information about my copyright/authorship attribution ideas, visit the corresponding pages of my sites: -- https://customsolvers.com/copyright/
-ES: https://customsolvers.com/copyright_es/ -- https://varocarbas.com/copyright/
ES: https://varocarbas.com/copyright_es/ diff --git a/all_binaries/UnitParser.jar b/binaries/UnitParser.jar similarity index 100% rename from all_binaries/UnitParser.jar rename to binaries/UnitParser.jar diff --git a/all_binaries/UnitParser_without_javadoc.jar b/binaries/UnitParser_without_javadoc.jar similarity index 100% rename from all_binaries/UnitParser_without_javadoc.jar rename to binaries/UnitParser_without_javadoc.jar diff --git a/all_code/UnitParser/.classpath b/code/UnitParser/.classpath similarity index 100% rename from all_code/UnitParser/.classpath rename to code/UnitParser/.classpath diff --git a/all_code/UnitParser/.project b/code/UnitParser/.project similarity index 100% rename from all_code/UnitParser/.project rename to code/UnitParser/.project diff --git a/all_code/UnitParser/.settings/org.eclipse.core.resources.prefs b/code/UnitParser/.settings/org.eclipse.core.resources.prefs similarity index 100% rename from all_code/UnitParser/.settings/org.eclipse.core.resources.prefs rename to code/UnitParser/.settings/org.eclipse.core.resources.prefs diff --git a/all_code/Test/.settings/org.eclipse.jdt.core.prefs b/code/UnitParser/.settings/org.eclipse.jdt.core.prefs similarity index 100% rename from all_code/Test/.settings/org.eclipse.jdt.core.prefs rename to code/UnitParser/.settings/org.eclipse.jdt.core.prefs diff --git a/all_code/Test/.settings/org.eclipse.ltk.core.refactoring.prefs b/code/UnitParser/.settings/org.eclipse.ltk.core.refactoring.prefs similarity index 100% rename from all_code/Test/.settings/org.eclipse.ltk.core.refactoring.prefs rename to code/UnitParser/.settings/org.eclipse.ltk.core.refactoring.prefs diff --git a/all_code/UnitParser/LICENSE b/code/UnitParser/LICENSE similarity index 100% rename from all_code/UnitParser/LICENSE rename to code/UnitParser/LICENSE diff --git a/all_code/UnitParser/META-INF/MANIFEST.MF b/code/UnitParser/META-INF/MANIFEST.MF similarity index 100% rename from all_code/UnitParser/META-INF/MANIFEST.MF rename to code/UnitParser/META-INF/MANIFEST.MF diff --git a/all_code/UnitParser/README.md b/code/UnitParser/README.md similarity index 100% rename from all_code/UnitParser/README.md rename to code/UnitParser/README.md diff --git a/all_code/UnitParser/build.xml b/code/UnitParser/build.xml similarity index 100% rename from all_code/UnitParser/build.xml rename to code/UnitParser/build.xml diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/CSharpOther.java b/code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/CSharpOther.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/CSharpOther.java rename to code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/CSharpOther.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/ExceptionInstantiation.java b/code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/ExceptionInstantiation.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/ExceptionInstantiation.java rename to code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/ExceptionInstantiation.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/Linq.java b/code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/Linq.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/Linq.java rename to code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/Linq.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/TryParseMethods.java b/code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/TryParseMethods.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/TryParseMethods.java rename to code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/TryParseMethods.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/TryParseOutput.java b/code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/TryParseOutput.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/TryParseOutput.java rename to code/UnitParser/src_Internal/InternalUnitParser/CSharpAdaptation/TryParseOutput.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Classes/BasicUnit.java b/code/UnitParser/src_Internal/InternalUnitParser/Classes/BasicUnit.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Classes/BasicUnit.java rename to code/UnitParser/src_Internal/InternalUnitParser/Classes/BasicUnit.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Classes/Compound.java b/code/UnitParser/src_Internal/InternalUnitParser/Classes/Compound.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Classes/Compound.java rename to code/UnitParser/src_Internal/InternalUnitParser/Classes/Compound.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Classes/CompoundPart.java b/code/UnitParser/src_Internal/InternalUnitParser/Classes/CompoundPart.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Classes/CompoundPart.java rename to code/UnitParser/src_Internal/InternalUnitParser/Classes/CompoundPart.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Classes/NumberInternal.java b/code/UnitParser/src_Internal/InternalUnitParser/Classes/NumberInternal.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Classes/NumberInternal.java rename to code/UnitParser/src_Internal/InternalUnitParser/Classes/NumberInternal.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitInfo.java b/code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitInfo.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitInfo.java rename to code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitInfo.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitPConstructor.java b/code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitPConstructor.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitPConstructor.java rename to code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitPConstructor.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitPartInternal.java b/code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitPartInternal.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitPartInternal.java rename to code/UnitParser/src_Internal/InternalUnitParser/Classes/UnitPartInternal.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Classes/XAndIntegerClass.java b/code/UnitParser/src_Internal/InternalUnitParser/Classes/XAndIntegerClass.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Classes/XAndIntegerClass.java rename to code/UnitParser/src_Internal/InternalUnitParser/Classes/XAndIntegerClass.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCCompounds.java b/code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCCompounds.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCCompounds.java rename to code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCCompounds.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCMain.java b/code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCMain.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCMain.java rename to code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCMain.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCOther.java b/code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCOther.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCOther.java rename to code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCOther.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCPrefixes.java b/code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCPrefixes.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCPrefixes.java rename to code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCPrefixes.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCUnits.java b/code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCUnits.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCUnits.java rename to code/UnitParser/src_Internal/InternalUnitParser/Hardcoding/HCUnits.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsCommon.java b/code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsCommon.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsCommon.java rename to code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsCommon.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsErrors.java b/code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsErrors.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsErrors.java rename to code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsErrors.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsHardcoding.java b/code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsHardcoding.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsHardcoding.java rename to code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsHardcoding.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsUnitP.java b/code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsUnitP.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsUnitP.java rename to code/UnitParser/src_Internal/InternalUnitParser/Methods/MethodsUnitP.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Operations/ConversionItems.java b/code/UnitParser/src_Internal/InternalUnitParser/Operations/ConversionItems.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Operations/ConversionItems.java rename to code/UnitParser/src_Internal/InternalUnitParser/Operations/ConversionItems.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Operations/Conversions.java b/code/UnitParser/src_Internal/InternalUnitParser/Operations/Conversions.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Operations/Conversions.java rename to code/UnitParser/src_Internal/InternalUnitParser/Operations/Conversions.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Operations/Equals.java b/code/UnitParser/src_Internal/InternalUnitParser/Operations/Equals.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Operations/Equals.java rename to code/UnitParser/src_Internal/InternalUnitParser/Operations/Equals.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Operations/Managed.java b/code/UnitParser/src_Internal/InternalUnitParser/Operations/Managed.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Operations/Managed.java rename to code/UnitParser/src_Internal/InternalUnitParser/Operations/Managed.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Operations/Operations.java b/code/UnitParser/src_Internal/InternalUnitParser/Operations/Operations.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Operations/Operations.java rename to code/UnitParser/src_Internal/InternalUnitParser/Operations/Operations.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Operations/OperationsOther.java b/code/UnitParser/src_Internal/InternalUnitParser/Operations/OperationsOther.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Operations/OperationsOther.java rename to code/UnitParser/src_Internal/InternalUnitParser/Operations/OperationsOther.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Operations/OperationsPublic.java b/code/UnitParser/src_Internal/InternalUnitParser/Operations/OperationsPublic.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Operations/OperationsPublic.java rename to code/UnitParser/src_Internal/InternalUnitParser/Operations/OperationsPublic.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/OtherParts/OtherPartsNumberParser.java b/code/UnitParser/src_Internal/InternalUnitParser/OtherParts/OtherPartsNumberParser.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/OtherParts/OtherPartsNumberParser.java rename to code/UnitParser/src_Internal/InternalUnitParser/OtherParts/OtherPartsNumberParser.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/OtherParts/OtherPartsNumberParserMethods.java b/code/UnitParser/src_Internal/InternalUnitParser/OtherParts/OtherPartsNumberParserMethods.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/OtherParts/OtherPartsNumberParserMethods.java rename to code/UnitParser/src_Internal/InternalUnitParser/OtherParts/OtherPartsNumberParserMethods.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Parse/Parse.java b/code/UnitParser/src_Internal/InternalUnitParser/Parse/Parse.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Parse/Parse.java rename to code/UnitParser/src_Internal/InternalUnitParser/Parse/Parse.java diff --git a/all_code/UnitParser/src_Internal/InternalUnitParser/Parse/ParseInfo.java b/code/UnitParser/src_Internal/InternalUnitParser/Parse/ParseInfo.java similarity index 100% rename from all_code/UnitParser/src_Internal/InternalUnitParser/Parse/ParseInfo.java rename to code/UnitParser/src_Internal/InternalUnitParser/Parse/ParseInfo.java diff --git a/all_code/UnitParser/src_Public/UnitParser/BinaryPrefixSymbols.java b/code/UnitParser/src_Public/UnitParser/BinaryPrefixSymbols.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/BinaryPrefixSymbols.java rename to code/UnitParser/src_Public/UnitParser/BinaryPrefixSymbols.java diff --git a/all_code/UnitParser/src_Public/UnitParser/BinaryPrefixValues.java b/code/UnitParser/src_Public/UnitParser/BinaryPrefixValues.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/BinaryPrefixValues.java rename to code/UnitParser/src_Public/UnitParser/BinaryPrefixValues.java diff --git a/all_code/UnitParser/src_Public/UnitParser/BinaryPrefixes.java b/code/UnitParser/src_Public/UnitParser/BinaryPrefixes.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/BinaryPrefixes.java rename to code/UnitParser/src_Public/UnitParser/BinaryPrefixes.java diff --git a/all_code/UnitParser/src_Public/UnitParser/MathematicalConstants.java b/code/UnitParser/src_Public/UnitParser/MathematicalConstants.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/MathematicalConstants.java rename to code/UnitParser/src_Public/UnitParser/MathematicalConstants.java diff --git a/all_code/UnitParser/src_Public/UnitParser/PhysicalConstants.java b/code/UnitParser/src_Public/UnitParser/PhysicalConstants.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/PhysicalConstants.java rename to code/UnitParser/src_Public/UnitParser/PhysicalConstants.java diff --git a/all_code/UnitParser/src_Public/UnitParser/Prefix.java b/code/UnitParser/src_Public/UnitParser/Prefix.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/Prefix.java rename to code/UnitParser/src_Public/UnitParser/Prefix.java diff --git a/all_code/UnitParser/src_Public/UnitParser/PrefixTypes.java b/code/UnitParser/src_Public/UnitParser/PrefixTypes.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/PrefixTypes.java rename to code/UnitParser/src_Public/UnitParser/PrefixTypes.java diff --git a/all_code/UnitParser/src_Public/UnitParser/PrefixUsageTypes.java b/code/UnitParser/src_Public/UnitParser/PrefixUsageTypes.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/PrefixUsageTypes.java rename to code/UnitParser/src_Public/UnitParser/PrefixUsageTypes.java diff --git a/all_code/UnitParser/src_Public/UnitParser/SIPrefixSymbols.java b/code/UnitParser/src_Public/UnitParser/SIPrefixSymbols.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/SIPrefixSymbols.java rename to code/UnitParser/src_Public/UnitParser/SIPrefixSymbols.java diff --git a/all_code/UnitParser/src_Public/UnitParser/SIPrefixValues.java b/code/UnitParser/src_Public/UnitParser/SIPrefixValues.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/SIPrefixValues.java rename to code/UnitParser/src_Public/UnitParser/SIPrefixValues.java diff --git a/all_code/UnitParser/src_Public/UnitParser/SIPrefixes.java b/code/UnitParser/src_Public/UnitParser/SIPrefixes.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/SIPrefixes.java rename to code/UnitParser/src_Public/UnitParser/SIPrefixes.java diff --git a/all_code/UnitParser/src_Public/UnitParser/UnitConversionFactors.java b/code/UnitParser/src_Public/UnitParser/UnitConversionFactors.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/UnitConversionFactors.java rename to code/UnitParser/src_Public/UnitParser/UnitConversionFactors.java diff --git a/all_code/UnitParser/src_Public/UnitParser/UnitP.java b/code/UnitParser/src_Public/UnitParser/UnitP.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/UnitP.java rename to code/UnitParser/src_Public/UnitParser/UnitP.java diff --git a/all_code/UnitParser/src_Public/UnitParser/UnitPart.java b/code/UnitParser/src_Public/UnitParser/UnitPart.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/UnitPart.java rename to code/UnitParser/src_Public/UnitParser/UnitPart.java diff --git a/all_code/UnitParser/src_Public/UnitParser/UnitSymbols.java b/code/UnitParser/src_Public/UnitParser/UnitSymbols.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/UnitSymbols.java rename to code/UnitParser/src_Public/UnitParser/UnitSymbols.java diff --git a/all_code/UnitParser/src_Public/UnitParser/UnitSystems.java b/code/UnitParser/src_Public/UnitParser/UnitSystems.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/UnitSystems.java rename to code/UnitParser/src_Public/UnitParser/UnitSystems.java diff --git a/all_code/UnitParser/src_Public/UnitParser/UnitTypes.java b/code/UnitParser/src_Public/UnitParser/UnitTypes.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/UnitTypes.java rename to code/UnitParser/src_Public/UnitParser/UnitTypes.java diff --git a/all_code/UnitParser/src_Public/UnitParser/Units.java b/code/UnitParser/src_Public/UnitParser/Units.java similarity index 100% rename from all_code/UnitParser/src_Public/UnitParser/Units.java rename to code/UnitParser/src_Public/UnitParser/Units.java diff --git a/all_code/Test/src/Parts/UnitParser.java b/code/UnitParser_Test.java similarity index 100% rename from all_code/Test/src/Parts/UnitParser.java rename to code/UnitParser_Test.java